Strings

Beginner25 min

Create strings, use escapes and raw strings, and read parts of a string with indexing and slicing.

What you will learn
  • Create strings with single, double and triple quotes
  • Use escape sequences and raw strings
  • Index and slice a string
  • Explain why strings are immutable
On this page

Almost every program handles text: names, messages, file contents. In Python all of that is the str type, and a few rules about it, such as quoting, slicing and immutability, are worth learning properly.

The fundamentals lesson on text explains characters, code points and encodings in general. Here we look at Python’s syntax for strings.

Creating strings

Single and double quotes are interchangeable, so you can pick whichever avoids a backslash. Triple quotes allow a string to span several lines.

quotes.py
single = 'It is'
double = "It's"
triple = """Line one
Line two"""
print(single, double)
print(triple)
Output
It is It's
Line one
Line two

Two string literals side by side are joined into one, which is occasionally useful for splitting a long literal over several lines:

adjacent_literals.py
print("ab" "cd")
Output
abcd

Escapes and raw strings

A backslash starts an escape sequence: \n is a newline, \t a tab, \\ a literal backslash, and \" a quote.

escapes.py
print("Tab:\tdone")
print("C:\new")
Output
Tab: done
C:
ew

That is why "C:\new" prints a line break in the middle of what looks like a Windows path. Put an r before the opening quote to make a raw string, where backslashes are left alone. Raw strings are handy for Windows paths and for regular expressions.

raw_string.py
print(r"C:\new")
Output
C:\new

Length, membership and repetition

len(text) counts characters, in tests for a substring, + joins two strings, and * repeats one.

string_operations.py
word = "Python"
print(len(word))
print("th" in word)
print("ha" * 3 + "!")
Output
6
True
hahaha!

Indexing and slicing

Each character has a position that starts at 0. Negative numbers count from the end, so word[-1] is the last character.

indexing.py
word = "Python"
print(word[0], word[-1])
Output
P n

A slice word[start:stop] takes characters from start up to, but not including, stop. You can leave either end out, and add a third number for the step: word[::-1] reverses the string.

slicing.py
word = "Python"
print(word[1:4])
print(word[:2], word[4:])
print(word[::-1])
Output
yth
Py on
nohtyP

Slices never raise an error for out-of-range ends, but an out-of-range single index does:

print("Python"[10])
Output
IndexError: string index out of range

The collections module teaches slicing in depth, and the same rules apply to lists and tuples.

Strings are immutable

You cannot change a string in place. Trying to assign to a position fails:

word = "Python"
word[0] = "J"
Output
TypeError: 'str' object does not support item assignment

Instead, build a new string and bind your name to it. This is the same name-and-object idea from the variables lesson.

new_string.py
word = "Python"
word = "J" + word[1:]
print(word)
Output
Jython

Common pitfalls

  • Adding a number to a string. "age: " + 30 raises TypeError. Convert with str(30) or, better, use an f-string (next lesson).
  • Windows paths without a raw string. "C:\new" contains a newline; "C:\Users" is worse, because \U begins a Unicode escape and is a syntax error.
  • Off-by-one in slices. word[1:4] has three characters, not four.
  • Expecting methods to modify the string. Methods such as upper() return a new string. The original is untouched.
ExerciseFour slices of one word

Given word = "Python", print four lines: the first three letters, the last three letters, the word reversed, and every second letter starting from the first.

Input: none. Expected output: Pyt, hon, nohtyP, Pto, one per line.

Show solution
four_slices.py
word = "Python"
print(word[:3])
print(word[-3:])
print(word[::-1])
print(word[::2])
Output
Pyt
hon
nohtyP
Pto

word[:3] stops before index 3. word[-3:] starts three from the end and runs to the finish. A step of 2 takes the letters at positions 0, 2 and 4.

ExercisePalindrome test

A palindrome reads the same forwards and backwards. For the word "racecar", print True if it is a palindrome and False if not, by comparing it with its reverse. Then change the word to "python" and check that you get False.

Input: none. Expected output for "racecar": True.

Show solution
palindrome.py
word = "racecar"
print(word == word[::-1])
Output
True

word[::-1] is the reversed text, and == asks whether it equals the original. With "python" the reverse is "nohtyp", so the answer is False. Ignoring capitals and punctuation needs string methods, which the lesson after next introduces.

Summary

  • Use any quote style, triple quotes for multi-line text, and r"..." to switch off escapes.
  • Index from 0, count from the end with negative numbers, and slice with [start:stop:step].
  • Strings are immutable: operations build new strings.

Next: f-strings.