StringsChapter 18 of 114
Concatenation
Joining strings with +, repeating with *, and why numbers need converting first.
Adding strings
+ glues two strings together. It adds nothing of its own, so spaces are up to you:
first = "Ada"
last = "Lovelace"
print(first + last)
print(first + " " + last)Output
AdaLovelace Ada Lovelace
Multiplying strings
* repeats:
print("ab" * 3)
print("-" * 20)Output
ababab --------------------
A row of dashes as a separator is the everyday use.
Numbers need converting
+ between a string and a number is an error, not an automatic conversion:
age = 36
print("Age: " + str(age))Output
Age: 36
Without str() that line raises TypeError: can only concatenate str (not "int") to str. Python refuses to guess whether you meant text or arithmetic.
print takes several arguments
Often you do not need to concatenate at all. print accepts a list of things and puts a space between them:
first = "Ada"
age = 36
print(first, age, "years")Output
Ada 36 years
You can change the separator and the ending:
print("a", "b", "c", sep="-")
print("no newline", end=" -> ")
print("same line")Output
a-b-c no newline -> same line
Adjacent literals join themselves
Two string literals next to each other are joined at compile time. This is only for literals, not variables, and it is how long text gets wrapped in source:
message = ("This is one long sentence that would not fit "
"comfortably on a single line of source code.")
print(message)Output
This is one long sentence that would not fit comfortably on a single line of source code.
names = ["Ada", "Grace" "Katherine"]
print(len(names))
print(names)Output
2 ['Ada', 'GraceKatherine']
Prefer f-strings
For anything with a variable in it, the next chapter's f-strings are shorter and much easier to read than a chain of +:
first = "Ada"
age = 36
print("Name: " + first + ", age " + str(age))
print(f"Name: {first}, age {age}")Output
Name: Ada, age 36 Name: Ada, age 36
Test yourself
2 questionsWhat does "Age: " + 36 do?
Show the answer
Raises TypeError — Python will not guess between text and arithmetic. Convert with str() or use an f-string.
What is len(["Ada", "Grace" "Katherine"])?
Show the answer
2 — A missing comma joins two adjacent literals silently. It is a real and quietly nasty bug.
f-Strings
Put values straight into text, and format them while you are there.