Skip to the content.
Home | Blog | Book Reading |About | All Courses

String Formatting


Here is the list of complete set of symbols which can be used along with “%”

%c character

>>> print ("%c" %'h')
h
>>> print ("%c" %104)
h
>>> print ("%c" %'"')
"
>>> print ("%c" %34)
"

%s string conversion via str() prior to formatting

>>> x = 'python'
>>> print("Hello %s , %s to SharetoLearn!" %(x,"Welcome"))
Hello python , Welcome to SharetoLearn!

%i signed decimal integer

>>> print("Hello %i + %i = %i" %(5,5,10))
Hello 5 + 5 = 10

%d signed decimal integer

>>> print("%d" % 100)
100
>>> print("%d" % 0b1111) #0b111 is binary value
15
>>> print("%03d" % 1) #padding" with zeroes is being done
001
>>> print("%03d" % 100.111)
100
>>> print("%03d" % 10.111)
010

%u unsigned decimal integer

>>> u'Hello\u0020Python ! '
u'Hello Python ! '
>>> u'Hello\u0021Python'
u'Hello!Python'

%o octal integer

>>> print "%o" % 012
12
>>> print "%o" % 10
12  # Because 012 ==12

%x hexadecimal integer (lowercase letters)

>>> print ("%x" % 10)
a
>>> print ("%x" % 11)
b
>>> print ("%x" % 12)
c

%X hexadecimal integer (UPPERcase letters)

>>> print ("%X" % 10)
A
>>> print ("%X" % 11)
B
>>> print ("%X" % 12)
C

%e exponential notation (with lowercase ‘e’)

>>> '%e' % 1234567890
'1.234568e+09'

%E exponential notation (with UPPERcase ‘E’)

>>> '%E' % 1234567890
'1.234568E+09'

%f floating point real number

>>> >>> print("Hello %.2f + %.2f = %.3f" %(5.1,5,10))
Hello 5.10 + 5.00 = 10.000

%g the shorter of %f and %e

>>> x = 1.23456789
>>> print '%e | %f | %g' % (x, x, x)
1.234568e+00 | 1.234568 | 1.23457

%G the shorter of %f and %E

>>> x = 1.23456789
>>> print '%E | %f | %G' % (x, x, x)
1.234568E+00 | 1.234568 | 1.23457