Hey pips! Manipulating strings – that’s the fancy programming term for text values – can often get a fiddly. There’s a good chance you’ve been taught something like this:

>>> name = input()
pypips

>>> message = "Hi there" + name + "!"

>>> print(message)
Hi there,pypips!

Here we use the add operator + to join (concatenate) the strings together. But wait, we want a space between Hi there, and our name! See, strings are exact, so every character matters. If we want whitespace we’ll need to explicitly include it:

>>> print("Hi there, " + name + "!")
Hi there, pypips!

We could achieve the same by passing each part straight to the inbuilt print() function, which will automatically concatenate the values together, adding a blank space " " separator between each.

>>> print("Hi there,", name, "!")
Hi there, pypips !

Oh, but now it’s added a space between our name and the exclamation mark too… so we’d have to use a combination instead:

>>> print("Hi there,", name + "!")
Hi there, pypips!

Yeah, that’s a bit messy ngl. If only there were a more streamlined and versatile way to incorporate dynamic values into strings.

Enter f-strings. No, they don’t contain rude words, but they start with an f before the opening quote mark:

>>> f_string = f"This works just like a regular string!"
>>> print(f_string)
This works just like a regular string!

This probably looks a bit weird, but like always, you’ll get used to it. You’ll probably also come to love it, because it makes string manipulation so easy. Want to incorporate the name variable into your message? Just wrap it in curly braces:

>>> print(f"Hi there, {name}!")
Hi there, pypips!

Anything between {} in an f-string will be evaluated just like regular Python code, converted to a string str, and inserted into the final string value. This is often known among programming languages as string interpolation.

Easy, right? And we can do this as much as we want without any increase in complexity:

>>> for i in range(1, 5):
...     print(f"{i} squared is {i ** 2}, {i} cubed is {i ** 3}")
1 squared is 1, 1 cubed is 1
2 squared is 4, 2 cubed is 8
3 squared is 9, 3 cubed is 27
4 squared is 16, 4 cubed is 64

Imagine having to build those sentences with +s or as multiple arguments to print(). Ew.

f-strings make your life so much easier, and mean it’s way easier to quickly see exactly how your text will be formatted.

print(f"Thanks for reading issue#{self.issue_index}, {self.email.recipient.name.capitalize()} :D")

Further Reading

You can specify the string separator between values to print()Python docs

There are actually characters other than f you can throw before the quote too – Python docs


Question? Bug needs fixing? Or just want to nerd out over programming?
Drop a message in the GitHub discussion for this issue.