Introduction to f-strings. And why you should start using them… | by Magdalena Konkiewicz | Nov, 2020
[ad_1]
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.
[ad_2]
Source link