Handle Variable printing – Format String

Now we’ll do even more typing of variables printing. This time we’ll use something called a “format string.” Every time you put " (double-quotes) around a piece of text you have been making a string. A string is how you make something that your program might give to a human. You print strings, save strings to files, send strings to web servers, and many other things.

Strings are really handy, so in this exercise you will learn how to make strings that have variables embedded in them. You embed variables inside a string by using specialized format sequences and then putting the variables at the end with a special syntax that tells Python, “Hey, this is a format string. Put these variables in there.”

As usual, just type this in even if you do not understand it and make it exactly the same.

domain = "pythoninhindi"
ext = "shiksha"

print (domain,".",ext)

Now lets check its output

you can see their is an extra space before and after “.”. As print put space when you give “,”.

But I don’t want space

We can do that with help of “format string” How?

We use %s symbol where we want to use a variable and define those %s later. Let’s see and example so you can understand clearly.

name = "Akar Periwal"
print ("My name is %s" % (name))

Print function only print whatever is in “”. We have defined %s in “” and told python to take value of it from % defined outside of “”. Confused? try this code and you will understand.

Multiple Format String

Its easy to use multiple format string, all you need to do is use multiple %s in your code and define variable in sequence.

domain = "pythoninhindi"
ext = "shiksha"

print ("Domain is %s and Ext is %s" % (domain, ext))

Now run this file and see the output. While using Format String you need to use variable in proper sequence.

Math Format String

Now lets take an advance example with Math format string

a = 2
b = 4
print ("%s %s" % (2 + 2, a * b))

Now run this and get the output. Output will be

akar:CH4 AkarPeriwal$ python3 ex1.py 
4 8
akar:CH4 AkarPeriwal$

So you can use Maths strings also in format strings and perform mathematical calculations.

Now let see solution of our problem in first code that is remove extra space before and after “.”

Code would look like

domain = "pythoninhindi"
ext = "shiksha"

print ("%s.%s" % (domain,ext))



no comments

Leave me comment