
The old way
Do you remember when you have learned about strings? You probably have defined a function hello_world similar to the code below:
def hello_world():
print("Hello, world!")
And then you progressed to write a function that could greet not the whole world but a particular person. Something similar to the definition below:
def hello_world(name):
print("Hello, " + name + "!")
Or even better-formatted version below:
def hello_world(name):
print("Hello, {}!".format(name))
F-strings offer another, even simpler, and even more readable version of the function above. Below we redefine the function using f-strings.
def hello_world(name):
print(f"Hello, {name}!")
As you can see the string is proceeded by the letter f and the variable name that needs to be inserted in the string is enclosed by curly brackets { }. No need for the .format() function anymore.
More Stories
How AI accelerated the discovery of Covid-19 Vaccines | by Rishabh Arora | Jan, 2021
Mastering Dictionaries And Sets In Python! | by Bharath K | Jan, 2021
OpenAI’s text-to-image engine, DALL-E, is a powerful visual idea generator