Formatting strings in Python using%

This article discusses formatting using%.

Formatting using% is similar to the formatting of printf in the C programming language.
% d — integer
% f — swim
% s — string
% x — hexadecimal
% o — octal

The following example describes the use of% formatting in Python

# Python program to demonstrate the use of formatting using%

 
# Initialize variable as string

variable = `15`

string = "Variable as string =% s" % (variable)

print string

 
# Print as raw data
# Thanks Himanshu Pan for that

print "Variable as raw data =% r" % (variable)

 
# Convert variable to integer
# And check other formatting options

 

variable = int (variable) # Without this below statement

# will throw an error.

string = " Variable as integer =% d " % ( variable)

print s tring

print "Variable as float =% f" % (variable)

  
# print any line or character after the sign
# here I use Mayank as the line

print "Variable as printing with special char =% cmayank" % (variable)

 

print "Variable as hexadecimal =% x" % (variable)

print "Variable as octal =% o" % (variable)

Output:

 Variable as string = 15 Variable as raw data = `15` Variable as integer = 15 Variable as float = 15.000000 Variable as printing with special char = mayank Variable as hexadecimal = f Variable as octal = 17 

This article contributed by Nikhil Kumar Singh (nickzuck_007)

Please post comments if you find anything incorrect, or you would like to share more information on the topic under discussion