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 = 'GyanByte'
year = 2019
print (f'This website: {website_name} has written this post in year: {year}')
>>> This website: GyanByte has written this post in year: 2019This is fantastic way of using string formatting, and is quite easily readable too.
By Placeholders
Lets look at above example
website_name = 'GyanByte'
year = 2019
print ('This website: %s has written this post in year: %d' %(website_name, year))
# Note: %s for string, and %d for integersPositional Formatting
Its kind of same as above. But, you use curly braces instead of percentage format.
website_name = 'GyanByte'
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: GyanByte has written this post in year: 2019. Thanks from GyanByte
print ('This website: {1} has written this post in year: {0}'.format(website_name, year))
>>> This website: 2019 has written this post in year: GyanByte
#Note: the position number in curly bracesBut, 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 numberingSimple Concatenation
You can concatenate strings simply by + operator.
s = 'hi' + ' ' + 'GyanByte'
print(s)
>>> 'hi GyanByte'This is a simple way, but doesn’t look good.












