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:
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:
print("it's fine")
print('she said "hello"')Output
it's fine she said "hello"
Triple quotes span lines
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:
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:
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:
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:
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:
word = "python"
word[0] = "P" # TypeError: 'str' object does not support item assignmentLooping over a string
A string is a sequence, so for walks its characters:
for letter in "abc":
print(letter)Output
a b c
Checking what is inside
in asks about substrings, not just single characters:
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:
sentence = "the quick brown fox"
print("Quick".lower() in sentence.lower())Output
True
Test yourself
2 questionsWhat 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.
Slicing
Take a piece out of a string with start, stop and step.