Python 3 - Magical Methods and Tricks with extremely useful methods
This post will show some really awesome tricks in python. Get the power of a…
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.
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.
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
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
You can concatenate strings simply by + operator.
s = 'hi' + ' ' + 'GyanBlog'
print(s)
>>> 'hi GyanBlog'
This is a simple way, but doesn’t look good.
This post will show some really awesome tricks in python. Get the power of a…
Introduction It is very important to introduce few process so that your code and…
While writing JUnit test cases, we encounter cases like we want to initialize a…
Introduction In this guide, we will see git basic commands, and fundamentals of…
Curl is a wonderful tool for initiate REST APIs or calls. Or, you can literally…
Introduction Consider a scenario where you are building a docker image on your…
Introduction This post has the complete code to send email through smtp server…
Introduction In a normal email sending code from python, I’m getting following…
Introduction In one of my app, I was using to talk to . I have used some event…
Introduction So you have a Django project, and want to run it using docker image…
Introduction It is very important to introduce few process so that your code and…
Introduction In this post, we will see a sample Jenkin Pipeline Groovy script…