Strings: Indexing and Slicing Text

Pick out characters by position, cut out slices, and see why string methods return new strings instead of changing the old one.

Python · beginner · 7 min · 8 steps · free

What you'll learn

strings.py

word = "python"
first = word[0]
last = word[-1]
middle = word[1:4]       # from index 1 up to, not including, 4
length = len(word)
shout = word + "!" * 3
upper = word.upper()     # a new string: the original never changes
print(first, last, middle, length, shout, upper, word)

Step by step

  1. A string of 6 characters: p y t h o n, at positions 0 to 5.
  2. Position 0 is the first character: "p".
  3. Negative positions count from the end: -1 is the last character, "n".
  4. A slice from position 1 up to, but not including, 4: "yth".
  5. len counts the characters: 6.
  6. + joins strings and * repeats one: "python!!!".
  7. .upper() returns a new string, "PYTHON". The original word is untouched.
  8. word is still "python" at the end. Indexing reads characters, slicing copies parts, and methods make new strings.

Common mistakes

Best practices

Key takeaways

Check yourself

What is "hello"[-2]?

Answer: "l". -1 is "o", so -2 is the "l" before it.

After s = "hi"; s.upper(), what is s?

Answer: "hi". The new "HI" was not saved anywhere; s is unchanged.

·

More in Python Basics