String Formatting in Python — 6 Things to Know About f-strings
Use f-strings to improve your string literals’ readability
When we learn any programming language, one of the first things we almost always do is to print the “Hello, World!” string. In learning Python, we pretty much do the same thing.
>>> # The very first function call!
>>> print("Hello, World!")
Hello, World!
In the above code, we use the built-in print()
function, which takes a string and prints the string to the output. Very straightforward, right?
What if we want to spice up the string and have some formatting for the string?
Fortunately (and not surprisingly), it’s possible with Python. Actually, there are multiple ways to do this, such as string concatenation, the modulo operator (%), and the string’s format()
method. For the sake of the present article, let’s just see the use of the format()
method, which is a flexible tool to manipulate strings. Consider the following trivial example.
>>> # A smarter function call
>>> person = "Danny"
>>> print("Hello, {}!".format(person))
Hello, Danny!
In the above code, we define a variable called person, to whom we want to say Hello. To do that, we use the format()
method to replace the field defined by…