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 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)
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)
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)
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
'''
Thanks. I am new to this blog.