Tuesday, March 6, 2018

String Formatting Operator


String Formatting Operator in Python 3


Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family.

Following is a simple example –

#!/usr/bin/python3
print ("My name is %s and weight is %d kg!" % ('Rama', 65))

And the output is –

My name is Rama and weight is 65 kg!

Here is the list of complete set of symbols which can be used along with %-
Format Symbol
conversion
%c
character
%s
String decimal integer
%d
Signed decimal integer
%u
Unsigned decimal integer
%o
Octal integer
%x
Hexadecimal integer (lower case letters)
%X
Hexadecimal integer (UPPER case letters)
%i
Signed decimal integer
%e
Exponential notation (with lowercase ‘e’)
%E
Exponential notation (with UPPER case ‘E’)
%f
Floating point real number
%g
The shorter of %f and %e
%G
The shorter of %f and %E

Other supported symbols and functionality are listed in the following table-
Symbol
Functionality
*
Argument specifies width or precision
-
Left justification
+
Display the sign
<sp>
Leave a blank space before a positive number
#
Add the octal leading zero (‘0’) or hexadecimal leading ‘0x’ or ‘0X’,depending on whether ‘x’ or ‘X’ were used.
0
Pad from left with zeros (instead of spaces)
%
‘%%’ leaves you with a single literal ‘%’
(var)
Mapping variable (dictionary arguments)
m.n.
m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)