4. Strings in Python

Strings in Python

A string is a sequence of characters: letters, digits, spaces, and symbols. Strings represent all the text your programs handle, from names to whole documents. This chapter covers how to create strings, pick them apart, and transform them.

Creating strings

You write a string inside matching single or double quotes. Both are equal; choose whichever avoids clashing with quotes inside the text. For text spanning several lines, use triple quotes:

PYTHON
a = 'hello'
b = "she said \"hi\""
c = """This string
spans two lines."""
print(a)
print(b)
print(c)
▸ OUTPUT
hello
she said "hi"
This string
spans two lines.

Indexing and slicing

Each character has a position called an index, starting at 0 for the first character. Negative indexes count from the end, where -1 is the last character. A slice [start:stop] returns the characters from start up to but not including stop.

PYTHON
word = "python"
print(word[0])
print(word[-1])
print(word[1:4])
print(word[:3])
print(word[3:])
▸ OUTPUT
p
n
yth
pyt
hon
p y t h o n 012 345 -6-5-4 -3-2-1

f-strings

The cleanest way to build a string that includes variable values is the f-string. Put the letter f before the opening quote and write expressions inside curly braces:

PYTHON
name = "Ada"
age = 25
print(f"{name} is {age} years old.")
print(f"Next year she will be {age + 1}.")
▸ OUTPUT
Ada is 25 years old.
Next year she will be 26.

Common string methods

Strings come with many built-in methods, called with a dot. Here are the ones you will use most.

MethodWhat it doesExampleResult
.upper()All uppercase"hi".upper()"HI"
.lower()All lowercase"HI".lower()"hi"
.strip()Remove surrounding spaces" hi ".strip()"hi"
.split()Break into a list"a b c".split()['a','b','c']
.replace()Swap text"cat".replace("c","h")"hat"
.find()Index of first match (-1 if none)"hello".find("l")2
PYTHON
line = "  Hello, World  "
print(line.strip().upper())
print("one,two,three".split(","))
▸ OUTPUT
HELLO, WORLD
['one', 'two', 'three']

Immutability

Strings are immutable: once created, they cannot be changed in place. Every method that seems to "change" a string actually returns a brand-new string, leaving the original untouched:

PYTHON
s = "cat"
s.upper()
print(s)
s = s.upper()
print(s)
▸ OUTPUT
cat
CAT

The first s.upper() created "CAT" but we did not store it, so s was unchanged. Only when we reassign s does the variable point to the new value. Remember this pattern: use the return value.