Strings

Python · Lesson 8 of 43 6 min read Updated

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.

PythonRun it yourself
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)
Output
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.

SequenceMeaning
\nNew line
\tTab
\\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:

PythonRun it yourself
broken = "C:\new\table.txt"
fixed = r"C:\new\table.txt"

print(broken)
print(fixed)
Output
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.

Text
 L   u   c   k   n   o   w
 0   1   2   3   4   5   6
-7  -6  -5  -4  -3  -2  -1
PythonRun it yourself
city = "Lucknow"

print(city[0])
print(city[3])
print(city[-1])
print(len(city))
Output
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.

PythonRun it yourself
vehicle = "HR12AB3456"

state = vehicle[:2]
district = vehicle[2:4]
number = vehicle[-4:]

print(state, district, number)
print(vehicle[::2])
print(vehicle[::-1])
Output
HR 12 3456
H1A35
6543BA21RH

The rules are simple once you see them:

  • Leave out start to begin at the start: vehicle[:2].
  • Leave out stop to 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:

PythonRun it yourself
city = "lucknow"
city = city[0].upper() + city[1:]
print(city)

greeting = "Hi " * 3
print(greeting + city)
print("now" in city, "Now" in city)
Output
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 is s[-1] or s[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. Use r"C:\new" or forward slashes.

Key points

  • Strings (str) are text inside single, double or triple quotes.
  • \n, \t and \\ are escape sequences; a raw string r"..." treats backslashes literally.
  • Indexes start at 0, and negative indexes count from the end.
  • s[start:stop:step] slices; stop is not included and [::-1] reverses.
  • Strings are immutable: make a new string instead of changing one.
  • len(), +, * and in work 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
Python
pnr = "4521876390"

print(pnr[:3])
print(pnr[-4:])
print(pnr[::-1])
print(len(pnr))
print("876" in pnr)
Output
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]?

2. What does "Kochi"[1:3] give?

3. What happens when you run name = "rohan" and then name[0] = "R"?

4. Which string keeps the backslashes exactly as typed?

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