Python String Formatting

String Formatting Operator %

>>> s = "Python"
>>> a = 1991

#this is old style formatting

>>> print("%s was developed in %d"%(s,a))
Python was developed in 1991

>>> x = 10.34567
>>> print('The value of x is %3.2f' %x)
The value of x is 10.35

>>> print('The value of x is %3.4f' %x)
The value of x is 10.3457

#truncating long string Old style
>>> print ("% 0.5s"%("hello world"))

#padding and aligning Old style
>>> print("%30s"%("hello world")) #right align	    
                   hello world

>>> print("%-30s"%("hello world")) #left align    
hello world
#numbers Old style
>>> print("%d"%(42))

>>> print("%f"%(42.56))

#padding numbers old style
>>> print("%4d"%(42))	    

>>> print("%04d"%(42)) #padded with 0    

>>> print("%06.2f"%(42.5689))	    

#signed numbers old style
>>> print("%+5d"%(42))	    

>>> print("% d"%(-42))	    

format() method :

The format() method is used to format the string as per requirement, it is very powerful ad versatile.

In format string we place the curly braces { } as placeholders which gets replaced.

We can use positional arguments or keyword arguments to specify the order.

Example :

# default arguments
>>> print("{}, was developed in {}.".format("Python", 1991))
Python, was developed in 1991.

In the above example, { } will be replaced with the order parameter in format() method.So, first {} will replace with "Python" and second {} will replace with 1991.

Example :

# positional arguments
>>> print("In {1}, {0} was developed.".format("Python", 1991))
In 1991, Python was developed.

In the above example, {1} will replace with 1991 and {0} will replace with "Python". format() method always positioned the values from 0, we can change the order of position in our formatted string.

Example :

# keyword arguments
>>> print("{language}, was developed in {year}.".format(language="Python", year=1991))
Python, was developed in 1991.

In the above example, within the {} specify the keyword and in format() method pass the corresponding value to the keywords.

Next topic is list


Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at

Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at

(8AM to 10PM):

+91-8527238801 , +91-9451396824

© 2017,, All rights reserved