Text: working with strings
A string is text. Anything in quotes is a string, and Python gives you a surprising amount of power over them.
Quotes
Single or double quotes both work. Pick one and be consistent:
print('single quotes')
print("double quotes")
single quotes double quotes
The choice matters in one situation — when the text itself contains a quote:
print("It's raining")
print('She said "hello"')
It's raining She said "hello"
Wrap in the other kind of quote and you never need to think about it again.
Joining text together
Adding strings sticks them end to end:
first = "Ada"
last = "Lovelace"
print(first + last)
print(first + " " + last)
AdaLovelace Ada Lovelace
Look at the first line. Python did exactly what you asked — it joined them with nothing in between. Spaces are not free. If you want one, you have to say so.
f-strings: the good way
Gluing strings with + gets ugly fast, especially with numbers mixed in. An
f-string lets you drop values straight into the text. Put an f before the
quote and wrap the values in { }:
name = "Ada"
age = 36
print(f"{name} is {age} years old")
print(f"Next year she will be {age + 1}")
Ada is 36 years old Next year she will be 37
The second line shows the real power: you can do maths inside the braces. f-strings are how modern Python builds text — use them everywhere.
Useful things strings can do
Strings carry their own tools, reached with a dot:
shout = "hello there"
print(shout.upper())
print(shout.title())
print(shout.replace("there", "world"))
print(len(shout))
HELLO THERE Hello There hello world 11
len() is the odd one out — it wraps around the string instead of hanging off
it with a dot. You'll meet len() again with lists.
The mistake nearly everyone makes
Methods return a new string. They do not change the original:
name = "ada"
name.upper()
print(name)
ada
Nothing happened — or so it looks. name.upper() produced "ADA" and then
Python threw it away, because you never stored it. Strings in Python cannot be
changed once made; you can only build new ones.
Store the result:
name = "ada"
name = name.upper()
print(name)
ADA
This trips up almost every beginner at least once. When a string method "doesn't work", check whether you kept what it gave back.
Text that looks like a number
From lesson 1: "13" and 13 are different things. Now you can convert:
answer = "42"
print(answer + "!")
print(int(answer) + 1)
42! 43
int() turns text into a number; str() goes the other way. Try answer + 1
and read the error — Python tells you plainly that it will not add a number to
text.
Prefer learning with a teacher?
WasiLearn Academy runs small-group classes covering this material, online and in Karachi.
See the classes