String formatting
Let's start off with a reminder of what we already know about the string data type in Python:
To create a string value, we wrap characters inside quotes, either double quotes or single quotes. Either is fine, as long as we're consistent with what we use for each string.
singer = 'Janelle Monáe'
play_song("Older", "Ben Platt")
To concatenate two strings together, we use the +
operator. That works as long as both operands are strings, even if one of them is a variable containing a string.
lyric = "If you're happy and you know it, " + "clap your hands!"
start = "If you're happy and you know it, "
lyric1 = start + "clap your hands!"
lyric2 = start + "wiggle your toes!"
lyric3 = start + "hug a friend!"
Escape sequences
If the string contains the same quote character that is being used to surround the string, then that quote character must be escaped. That means we must use a special character to let Python know to not treat the quote character normally (since treating it normally would end the string).
This string is broken and results in a syntax error:
greeting = 'how're you doing?'
To fix it, insert a backslash right before the single quote:
greeting = 'how\'re you doing?'
The backslash is what is known as the escape character, and is used as the escape character in many languages. That means if you do want an actual backslash in a string, you need to escape the backslash with yet another backslash:
path = "C:\\My Documents"
There are also a few special escape sequences that produce something other than a standard character. The most useful sequence is "\n"
, which creates a new line in the string once it's printed out.
Here's a string storing a famous haiku by Matsuo Bashō:
haiku = "An old silent pond\nA frog jumps into the pond—\nSplash! Silence again."
Calling print(haiku)
results in:
An old silent pond
A frog jumps into the pond—
Splash! Silence again.
The other most useful escape sequence is "\t"
for inserting a tab character into a string.
String conversion
The code below attempts to concatenate a string with a number:
count = 3
noun = 'cat'
plural = 'I have ' + count + ' ' + noun + 's'
Sadly, that's en error! Python lets you use the +
operator between two numbers and between two strings, but not between a number and a string.
One approach is to convert the number to a string, by calling the globally available str()
on it.
plural = 'I have ' + str(count) + ' ' + noun + 's'
You can use str()
in any situation where a function or operator expects a string but all you have is a number or some other data type.
F strings
Since programmers very often need to create new strings from a mish-mash of strings, numbers, and other variables, Python offers multiple ways to do string formatting. The most modern technique, and my own personal favorite, is f strings.
An f string starts with an "f" in front of the quotes, and then uses curly brackets to surround Python expressions inside the string. See this example:
greeting = "Ahoy"
noun = "Boat"
sentence = f"{greeting}, {noun}yMc{noun}Face"
Python evaluates the expressions inside each curly bracket, turning that whole string into "Ahoy, BoatyMcBoatFace".
If the expression results in a numeric value, Python will take care of the string conversion for you:
month = "June"
day = "24"
year = "1984"
sentence = f"I was born {month} {day}th {year}"
The coolest thing about f strings is that you can put any valid expression inside those curly brackets - not just variable names.
quantity = 3
price = 9.99
cashier_says = f"The total for your {quantity} meals will be {quantity * price}"