Strings
Text is everywhere in programs: names, addresses, messages, file paths, PNR numbers. In Python, a piece of text is a string, and the type is str. Strings are one of the types you will use most, so it pays to understand them well.
In this lesson you will create strings, include special characters in them, pick out single characters and pieces with indexing and slicing, and learn why strings can never be changed in place.
Creating strings
Put text inside single quotes '...' or double quotes "...". Both make exactly the same kind of string. Pick the one that saves you from escaping: if the text contains an apostrophe, wrap it in double quotes.
city = "Jaipur"
shop = 'Meera\'s Sweets'
review = "Meera's kaju katli is the best in town"
address = """Meera's Sweets
12, Johari Bazaar
Jaipur 302003"""
print(shop)
print(review)
print(address)Meera's Sweets Meera's kaju katli is the best in town Meera's Sweets 12, Johari Bazaar Jaipur 302003
Triple quotes, """...""" or '''...''', let a string run over several lines. The line breaks become part of the string. In the second line, \' puts an apostrophe inside single quotes; the double-quoted version on the third line is easier to read.
Escape sequences and raw strings
A backslash \ inside a string starts an escape sequence: a two-character code for a character that is hard to type.
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | One backslash |
\' and \" | A quote of the same kind as the string |
This causes a classic bug with Windows file paths, where \n and \t turn into a new line and a tab:
broken = "C:\new\table.txt"
fixed = r"C:\new\table.txt"
print(broken)
print(fixed)C: ew able.txt C:\new\table.txt
The r before the quote makes a raw string, where backslashes are ordinary characters. Use raw strings for Windows paths and for regular expressions, which you will meet in Regular Expressions. For file paths, the pathlib module is even better, and you will use it in Reading & Writing Files.
Indexing: one character at a time
Every character in a string has a position number called an index. Counting starts at 0, not 1. You can also count from the end with negative numbers: -1 is the last character.
L u c k n o w
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1city = "Lucknow"
print(city[0])
print(city[3])
print(city[-1])
print(len(city))L k w 7
len() gives the number of characters. The last index is always len(city) - 1, here 6. Asking for city[7] stops the program with IndexError: string index out of range, because there is no position 7.
Slicing: a piece of a string
A slice gives you part of a string. Write [start:stop]: you get the characters from start up to, but not including, stop.
vehicle = "HR12AB3456"
state = vehicle[:2]
district = vehicle[2:4]
number = vehicle[-4:]
print(state, district, number)
print(vehicle[::2])
print(vehicle[::-1])HR 12 3456 H1A35 6543BA21RH
The rules are simple once you see them:
- Leave out
startto begin at the start:vehicle[:2]. - Leave out
stopto go to the end:vehicle[-4:]is the last four characters. - A third number is the step:
[::2]takes every second character, and[::-1]walks backwards, which reverses the string.
Unlike indexing, slicing never raises an error. A slice that goes past the end just stops at the end, and vehicle[20:] gives an empty string "".
Strings cannot be changed
Strings are immutable: once a string exists, its characters cannot be changed. Trying city[0] = "l" gives TypeError: 'str' object does not support item assignment. Instead, build a new string and assign it to the variable:
city = "lucknow"
city = city[0].upper() + city[1:]
print(city)
greeting = "Hi " * 3
print(greeting + city)
print("now" in city, "Now" in city)Lucknow Hi Hi Hi Lucknow True False
+ joins strings together, * repeats a string, and the in operator checks whether one string appears inside another. Notice that in is case-sensitive: "Now" is not in "Lucknow".
Strings are Unicode
Python 3 strings are Unicode, which means they can hold text in any language, plus symbols such as ₹. You can store Hindi, Tamil or Malayalam text as easily as English.
There is one detail to know. len() counts code points, the separate Unicode characters, which is not always what a reader sees as one letter. The Hindi word "नमस्ते" gives len() of 6, more than the letters a reader sees, because each vowel sign and the halant (्) is a separate code point. This matters if you limit the length of names or messages in other scripts.
Common mistakes
- Starting to count at 1. The first character is
s[0], and the last iss[-1]ors[len(s) - 1]. - Expecting the slice to include
stop."Python"[0:2]is"Py", two characters, not three. - Trying to change a character.
s[0] = "X"fails; build a new string with slicing and+. - Backslashes in Windows paths.
"C:\new"contains a new line. User"C:\new"or forward slashes.
Key points
- Strings (
str) are text inside single, double or triple quotes. \n,\tand\\are escape sequences; a raw stringr"..."treats backslashes literally.- Indexes start at 0, and negative indexes count from the end.
s[start:stop:step]slices;stopis not included and[::-1]reverses.- Strings are immutable: make a new string instead of changing one.
len(),+,*andinwork on strings; Python strings handle every language.
Exercise
A PNR number for a train ticket is stored as pnr = "4521876390". Print the first three digits, the last four digits, and the whole number with the digits reversed. Then print how many digits it has, and check whether "876" appears inside it.
Show solution
pnr = "4521876390"
print(pnr[:3])
print(pnr[-4:])
print(pnr[::-1])
print(len(pnr))
print("876" in pnr)452 6390 0936781254 10 True
[:3] and [-4:] slice from the start and the end, [::-1] reverses the string, and in checks for a smaller string inside a bigger one.
Quick Quiz
1. For word = "Python", what is word[1]?
Indexes start at 0, so index 1 is the second character.
2. What does "Kochi"[1:3] give?
The slice starts at index 1 and stops before index 3.
3. What happens when you run name = "rohan" and then name[0] = "R"?
Strings are immutable, so you cannot assign to one character.
4. Which string keeps the backslashes exactly as typed?
The r prefix makes a raw string, where backslashes do not start escape sequences.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
