Chapters
Python114 chapters

StringsChapter 15 of 114

Strings

Text in Python, the quotes you can use, and the fact that strings never change.

Quotes

Text goes in quotes. Single and double do exactly the same thing:

Python
first = "Ada"
second = 'Lovelace'
print(first, second)

Output

Ada Lovelace

Having both is useful, because it lets you put one kind inside the other without any escaping:

Python
print("it's fine")
print('she said "hello"')

Output

it's fine
she said "hello"

Triple quotes span lines

Python
note = """Dear Ada,
The engine works.
"""
print(note)

Output

Dear Ada,
The engine works.

The line breaks you type are part of the string, which is why the output ends with a blank line — there is a newline before the closing quotes.

Length and indexing

len() counts characters. Indexing pulls one out, counting from zero:

Python
word = "python"
print(len(word))
print(word[0])
print(word[5])

Output

6
p
n

Negative indexes count from the right, which saves the arithmetic:

Python
word = "python"
print(word[-1])
print(word[-2])

Output

n
o

Strings never change

This is the property that explains most string behaviour. A string cannot be edited in place:

Python
word = "python"
print(word.upper())
print(word)

Output

PYTHON
python

upper() did not change word. It built a new string and handed it back. If you want to keep the result, assign it:

Python
word = "python"
word = word.upper()
print(word)

Output

PYTHON

Trying to edit in place is an error rather than a surprise, which is at least honest:

Python
word = "python"
word[0] = "P"   # TypeError: 'str' object does not support item assignment

Looping over a string

A string is a sequence, so for walks its characters:

Python
for letter in "abc":
    print(letter)

Output

a
b
c

Checking what is inside

in asks about substrings, not just single characters:

Python
sentence = "the quick brown fox"
print("quick" in sentence)
print("slow" in sentence)
print("Quick" in sentence)

Output

True
False
False

The last one is False because comparison is case sensitive. Lowercase both sides when you do not care:

Python
sentence = "the quick brown fox"
print("Quick".lower() in sentence.lower())

Output

True

Test yourself

2 questions

What does word.upper() do to word?

Show the answer

Nothing; it returns a new string — Strings are immutable. Assign the result back if you want to keep it.

For word = "python", what is word[-1]?

Show the answer

"n" — Negative indexes count from the right, so -1 is the last character.

Next chapter

Slicing

Take a piece out of a string with start, stop and step.