DEV Community

Cover image for Easy use of F-Strings with Python.
Sam Sonter
Sam Sonter

Posted on • Edited on

Easy use of F-Strings with Python.

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 mode Exit 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 mode Exit fullscreen mode

I got rid of the format method and introduced the F string. I now put the variables inside the placeholders 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 mode Exit fullscreen mode

The next 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 mode Exit 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

Top comments (2)

Collapse
 
ericlecodeur profile image
Eric Le Codeur • Edited

Hi, thanks for this post.

A quick advice, If you add the word python after your 3 tics, the code will be highlight in color

'''python
your code
'''

Collapse
 
asapsonter profile image
Sam Sonter

Thanks. I am new to this blog.