Aug 12, 2019

Format strings | Python programming

Format strings are used to format the printing output. We can print a string with variables in it. You know we can print a normal string with print() function. In our printing tutorial we saw that print() function accept a string as an argument . Do you know , we can supply that string with embedded variables. First of all take a look at following script.
[email protected]:~/programming$ cat tmp1.py
#!/usr/bin/env python
x = 3
print ("value of x is %d" % x)
print ("value of x+3 is %d"% (x+3))

[email protected]:~/programming$ python tmp1.py
value of x is 3
value of x+3 is 6

[email protected]:~/programming$ python3 tmp1.py
value of x is 3
value of x+3 is 6
Give your focus on following line of code. print ("value of x is %d" % x) You know that we indicate a string by adding two " s around it. But there is a %d inside the string. When print() function see it , the function don't print it and it expect a decimal number after the string. Yes you are correct, d stands for a decimal. Now after the string we add another % symbol and put our integer variable there. So when print() function see %d it assume we are going to print a decimal in string. So it will check for a decimal after string. It will pickup that decimal and put it on the right place in string. After it will printed in correct format. Not only decimals. We can print any variables like string, floats etc.Also we can add any number of variables in a string at once. Let's see how.
[email protected]:~/programming$ cat tmp1.py
#!/usr/bin/env python
x = 5
y = "HacksLand"
print ("our variable string is %s " % y)
print ("integer is %d while string is %s " % (x , y))

[email protected]:~/programming$ python tmp1.py
our variable string is HacksLand 
integer is 5 while string is HacksLand 

[email protected]:~/programming$ python3 tmp1.py
our variable string is HacksLand 
integer is 5 while string is HacksLand 
Hear we have another example of format strings with decimals.
[email protected]:~/programming$ cat tmp1.py
#!/usr/bin/env python
a = 3
b = 4
print ('Sum of %d and %d is %d ' %(a , b , a+ b))

[email protected]:~/programming$ python tmp1.py
Sum of 3 and 4 is 7 

[email protected]:~/programming$ python3 tmp1.py
Sum of 3 and 4 is 7 
OK. Its all about format strings for this tutorial. This techniques will be used in next tutorials.

Jun 09
Functions in python programming

Functions are life savers. Yes they make our life easier. A function is a peace of code and used to....

Aug 12
Error Handling | Python Programming

Errors are absolutely normal when programming. You may get hundred of errors while learning. Not....

Aug 12
Cross Site Scripting Tutorial

Hello and welcome all. In our web application hacking tutorials now we have learned about SQLI....

Replying to 's comment Cancel reply