Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 7 of 25

Strings

A string is a sequence of characters. Each character has a position, called an index, starting from 0. Negative indexes count from the end, so -1 is the last character.

word = "python"
print(word[0], word[-1])   # p n

Slicing takes a part of a string: word[1:4] gives the characters at positions 1, 2 and 3. Leaving out a number means "from the start" or "to the end", and word[::-1] reverses the string.

Strings have many built-in methods. They return a new string and never change the original, because strings cannot be changed in place.

  • len(s) counts the characters
  • s.upper(), s.lower(), s.title() change letter case
  • s.replace("a", "b") swaps text
  • s.count("a") counts occurrences
  • "a" in s checks whether "a" appears

Key takeaways

  • len(s) counts the characters. Positions start at 0, so s[0] is the first character and s[-1] is the last.
  • A slice such as s[1:4] takes positions 1, 2 and 3. The end position is not included.
  • String methods such as upper(), replace() and count() return a new string. The original does not change.
  • "a" in s checks whether some text appears inside another string.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.