Python 3 - Format String fun

May 14, 2019

This post is dedicated for cases where we intend to append a variable value in a string, whether in logs, string message etc.

Use Format String

Just put a character f before your string, and put all variable in between curly braces.

Example

website_name = 'GyanBlog'
year = 2019

print (f'This website: {website_name} has written this post in year: {year}')

>>> This website: GyanBlog has written this post in year: 2019

This is fantastic way of using string formatting, and is quite easily readable too.

By Placeholders

Lets look at above example

website_name = 'GyanBlog'
year = 2019

print ('This website: %s has written this post in year: %d' %(website_name, year))

# Note: %s for string, and %d for integers

Positional Formatting

Its kind of same as above. But, you use curly braces instead of percentage format.

website_name = 'GyanBlog'
year = 2019

print ('This website: {} has written this post in year: {}'.format(website_name, year))

You can use numbers in curly braces if you want to specify which variables comes when:

print ('This website: {0} has written this post in year: {1}. Thanks from {0}'.format(website_name, year))
>>> This website: GyanBlog has written this post in year: 2019. Thanks from GyanBlog

print ('This website: {1} has written this post in year: {0}'.format(website_name, year))
>>> This website: 2019 has written this post in year: GyanBlog

#Note: the position number in curly braces

But, you can not mix them!

print ('This website: {1} has written this post in year: {}'.format(website_name, year))

# error: ValueError: cannot switch from manual field specification to automatic field numbering

Simple Concatenation

You can concatenate strings simply by + operator.

s = 'hi' + ' ' + 'GyanBlog'
print(s)

>>> 'hi GyanBlog'

This is a simple way, but doesn’t look good.


Similar Posts

Latest Posts