String indexing and slicing are the two operations that you will perform on text more often than anything else. Both of them have rules that are worth learning once instead of rediscovering them under pressure. Positions start at zero, negative positions count back from the end, the stop value of a slice is always excluded, and a slice that reaches outside the string is quietly clipped instead of raising an error. There is also one Unicode surprise at the end, and it breaks more production code than any of the others.
This is the first lesson in the Python Strings module, and the next lesson in this module is about "The String Methods You Use Every Day".
How does string indexing work?
A string behaves like a sequence of characters, and every character has a position. The first character is at position 0, the second is at position 1, and so on. Negative positions count back from the end, so -1 is the final character and -2 is the one before it. There is no separate "last character" property, because text[-1] is the usual way to say it in Python.
word = 'Tutorsbot'
print('word ->', word)
print('word[0] ->', word[0])
print('word[1] ->', word[1])
print('word[-1] ->', word[-1])
print('word[-2] ->', word[-2])
print('len(word) ->', len(word))
try:
print(word[99])
except IndexError as error:
print('word[99] ->', error)
print('ord and chr ->', ord('A'), chr(65))
Indexing past the end raises IndexError, which is Python refusing to invent a character that is not there. The ord() and chr() pair converts between a character and the integer code point that represents it, and that is occasionally the only way to look at a character that is misbehaving.
What does a slice actually do?
Slicing uses square brackets and up to three parts that are separated by colons: text[start:stop:step]. The start is included, the stop is excluded, and the step controls the direction and the spacing. Anything that you leave out takes a sensible default. The start defaults to the beginning, the stop defaults to the end, and the step defaults to 1.
word = 'Tutorsbot'
print('word[0:5] ->', word[0:5])
print('word[5:] ->', word[5:])
print('word[:3] ->', word[:3])
print('word[::2] ->', word[::2])
print('word[::-1] ->', word[::-1])
print('word[-3:] ->', word[-3:])
print('word[3:3] ->', repr(word[3:3]))
print('word[:100] ->', word[:100])
Two behaviours stand out here. An empty slice gives you an empty string rather than an error, so word[3:3] is ''. And a slice whose bounds run past the end of the string is clipped to whatever actually exists, so word[:100] is simply the whole string. Slicing is forgiving in a way that indexing is not, and that is why text[start:start + length] never raises an error, even when the length is only a guess.
The three-part form earns its keep in two situations. A step of 2 takes every other character, and a step of -1 reverses the string, which is the standard way to write text[::-1].
There is a cost to remember as well. A slice copies the characters that it selects, so slicing a very long string is not free, and slicing it inside a loop copies it many times over. If you need one character, index it. If you need a chunk, slice it once and keep the result instead of working out the same slice again inside the loop.
The classic off-by-one mistake is pulling a file extension off the end of a name. name.rfind('.') finds the last dot, and the extension is everything after it, but only when that dot exists and is not the very first character. Getting that right takes two checks instead of one, which is one of the reasons that the pathlib module exists.
Why can you not assign to a string position?
Because strings are immutable. Once a string exists, its characters cannot be changed. Every slice produces a brand new string, and trying to write into an existing one is an error.
original = 'hello'
piece = original[1:4]
print('original ->', original)
print('piece ->', piece)
print('same object? ->', piece is original)
try:
original[0] = 'H'
except TypeError as error:
print('assignment ->', error)
This is less of a limitation and more of a guarantee. Because no string can change underneath you, you can share a string safely between functions, cache it in a dictionary, or use it as a key. The price is that editing a string means creating a new one, and that is why the usual approach is to build the new value and rebind the name. The next-but-one lesson looks at why the language is built this way.
How do you handle Unicode and emoji correctly?
A Python string is a sequence of Unicode code points, and not a sequence of the characters that a human sees on the screen. For plain text the difference never shows up. For emoji it is dramatic, because one visible character can be several code points joined together.
# A family emoji is built from several code points.
family = '\U0001F468\u200D\U0001F469\u200D\U0001F467'
print('family emoji length ->', len(family))
accented = 'café'
print('accented chars ->', len(accented))
print('accented bytes ->', len(accented.encode('utf-8')))
The family emoji above is five code points long, and the accented word is four characters but five bytes. Slicing one of those strings can cut a visible character in half, and that is how a stored user name ends up with a stray half emoji inside it.
For plain-language work, indexing and slicing are exactly right. When you are handling user-typed names, titles, or reactions where the input may contain emoji or combining characters, count grapheme clusters instead, and reach for a library that does that hard work for you rather than trying to detect the clusters yourself.
Your turn: build a slicing toolkit
- Write
head(text, size)to return the firstsizecharacters, andtail(text, size)to return the last ones. Handle a size of zero without raising an error. - Write
reverse(text)andevery_other(text)using nothing but slicing. Check thatreverse('abc')gives'cba'and thatevery_other('abcdef')gives'ace'. - Write
middle(text)that returns the text with the first and the last characters removed, and confirm that it returns an empty string for a one-character input instead of raising an error. - Add
safe_char(text, index)that returns the character at a position, or a fallback string when the position is out of range. Call it with a positive index, with a negative index, and with a wildly out-of-range index. - Finally, write
truncate(text, limit)that shortens text to a limit and appends an ellipsis when it had to cut, without ever splitting a multi-code-point emoji in half. Test it with a name that contains an emoji.
Slicing cheat sheet
- Positions start at zero, and negative positions count back from the end.
- Indexing out of range raises
IndexError, while slicing out of range is clipped. - A slice is
text[start:stop:step], with an included start and an excluded stop. - Omitted parts default to the beginning, the end, and a step of 1.
text[::-1]reverses a string, andtext[::2]takes every other character.- A slice is always a new string, characters cannot be assigned, and
len()counts code points rather than visible characters.