This content originally appeared on DEV Community and was authored by Sam Sonter
F-Strings
Here, I am going to jump straight to printing out strings with Python. Take a look at this code using place holder format method.
first_name = 'sam'
last_name = 'sonter'
intro = "My name is {} {}".format (first_name,last_name)
print(intro)
output: My name is sam sonter
Python can also allow us to use the F-String to get same output. Check this out.
first_name = 'sam'
last_name = 'sonter'
intro = f"My name is {first_name} {last_name}"
print(intro)
output: My name is sam sonter
I got ride of the format method and introduced the F string. I now put the variables inside the place holders making the block of code easier to understand.
Now, I am going to use a dictionary in the next example.
person = {'name': 'Sam', 'height': 188}
sentence = "My name is {} I am {} cm tall".format(person['name'],person['age'])
print(sentence)
This example is pretty much the same with the first one except here we are using a dictionary. Now, let's use the F string.
person = {'name': 'Sam', 'height': 188}
sentence = f"My name is {person['name']} I am {person['height']} cm tall"
print(sentence)
Many people might make syntax errors by using the wrong quotes. If you pay attention you can see i used double " outside my statement and single ' inside the statement to avoid syntax errors.
That is it for this article, thanks for reading and I hope you find this useful.
Sam Sonter
This content originally appeared on DEV Community and was authored by Sam Sonter
Sam Sonter | Sciencx (2021-11-15T01:48:12+00:00) Easy use of F-Strings with Python.. Retrieved from https://www.scien.cx/2021/11/15/easy-use-of-f-strings-with-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.