Fundamentals · Lesson 6 of 94

Strings: text, indexing, and slicing

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

A string is a sequence of characters. You write one between quotes, and Python does not care whether they are 'single' or "double", as long as they match. That freedom is useful: if the text contains an apostrophe, wrap it in double quotes, and if it contains double quotes, wrap it in single ones. Triple quotes, """, let a string span several lines.

Some characters cannot be typed directly, so you escape them with a backslash. \n is a new line, \t is a tab, and \" is a literal quote inside a double-quoted string. You will see \n constantly, because it is how text files mark the end of a line.

Because a string is a sequence, every character has a position, called an index. Indexes start at 0, not 1, so the first character of "Python" is at index 0 and the last is at index 5. Negative indexes count from the end: -1 is the last character, -2 the one before it.

Strings: text, indexing, and slicing: P; 0 / -6 → y; 1 / -5 → t; 2 / -4 → h; 3 / -3 → o; 4 / -2 → n; 5 / -1
Strings: text, indexing, and slicing · Figure 1 · Open for full size

A slice takes a range: text[start:stop] gives the characters from start up to but not including stop. Leaving out start means from the beginning, leaving out stop means to the end. The stop-is-excluded rule feels odd for about a day and then becomes natural, because text[:3] is exactly three characters and text[3:] is the rest.

Two operators work on strings the way they work on numbers, with a twist. + joins strings end to end, and * repeats a string a whole number of times, so "ab" * 3 is "ababab". The in operator asks whether one string appears inside another and answers True or False, and len() counts the characters. These four cover most of what you do with text before you reach string methods in the next lesson.

Strings are immutable: once created, a string cannot be changed. You cannot assign to text[0]. Every operation that looks like it changes a string, such as making it uppercase, actually builds a new string and hands it back. This is a feature: it means a string you pass to someone else's code cannot be altered underneath you.

Code

Start with the ways of writing a string. Note how the quote style changes to fit the content, and how the escapes come out in the output.

# quotes.py
single = 'It works'
double = "It's easier with double quotes"
multi = """Line one
Line two"""

print(single)
print(double)
print(multi)
print("Tab:\tafter tab")
print("She said \"hi\"")
Output
It works
It's easier with double quotes
Line one
Line two
Tab:	after tab
She said "hi"

Indexing picks one character. Compare the positive and negative forms, and see what len() reports so you know the valid range.

# indexing.py
word = "Python"

print(len(word))
print(word[0])
print(word[5])
print(word[-1])
print(word[-6])
Output
6
P
n
n
P

Slicing takes a range. Each line here uses one common pattern: a fixed range, from the start, to the end, from the back, and a step of two.

# slicing.py
word = "Python"

print(word[0:3])
print(word[:3])
print(word[3:])
print(word[-3:])
print(word[::2])
Output
Pyt
Pyt
hon
hon
Pto

Trying to change one character raises an error. That error is the language protecting you; the working approach is to build a new string.

# immutable.py
word = "Python"
word[0] = "J"
Output
Traceback (most recent call last):
  File "immutable.py", line 2, in <module>
    word[0] = "J"
    ~~~~^^^
TypeError: 'str' object does not support item assignment
# rebuild.py
word = "Python"
new_word = "J" + word[1:]

print(word)
print(new_word)
Output
Python
Jython

Try it yourself

Create slices.py with the string "programming". Print the first four characters, the last four, every second character, and the string reversed using a step of -1. Then work out, before running it, what word[3:-3] gives, and check.

Common mistakes

What's next

You can take strings apart. Next you will learn to clean them, search them, and build new text from variables with f-strings.

Course overview