1

Easy use of F-Strings with Python.

 2 years ago
source link: https://dev.to/asapsonter/easy-use-of-f-strings-with-python-55ja
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK