Strings
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.
single = 'It is'double = "It's"triple = """Line oneLine two"""
print(single, double)print(triple)It is It'sLine oneLine twoTwo string literals side by side are joined into one, which is occasionally useful for splitting a long literal over several lines:
print("ab" "cd")abcdEscapes and raw strings
A backslash starts an escape sequence: \n is a newline, \t a tab, \\ a literal backslash, and \" a quote.
print("Tab:\tdone")print("C:\new")Tab: doneC:ewThat 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.
print(r"C:\new")C:\newLength, membership and repetition
len(text) counts characters, in tests for a substring, + joins two strings, and * repeats one.
word = "Python"print(len(word))print("th" in word)print("ha" * 3 + "!")6Truehahaha!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.
word = "Python"print(word[0], word[-1])P nA 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.
word = "Python"print(word[1:4])print(word[:2], word[4:])print(word[::-1])ythPy onnohtyPSlices never raise an error for out-of-range ends, but an out-of-range single index does:
print("Python"[10])IndexError: string index out of rangeThe 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"TypeError: 'str' object does not support item assignmentInstead, build a new string and bind your name to it. This is the same name-and-object idea from the variables lesson.
word = "Python"word = "J" + word[1:]print(word)JythonCommon pitfalls
- Adding a number to a string.
"age: " + 30raisesTypeError. Convert withstr(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\Ubegins 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.
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
word = "Python"print(word[:3])print(word[-3:])print(word[::-1])print(word[::2])PythonnohtyPPtoword[: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.
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
word = "racecar"print(word == word[::-1])Trueword[::-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.