In python, a string can be formatted using different methods, like −
And we are going to discuss the “%” string formatting option in this section.
String formatting comes in two flavors−
Formatting using % comes from the C type printf and support following types
>>> name = "Jeff Bezos" >>> "Richest person in the world is %s" %name 'Richest person in the world is Jeff Bezos'
Below is the one simple program to demonstrate the use of string formatting using % in python −
# %s - string var = '27' #as string string = 'Variable as string = %s' %(var) print(string) #%r - raw data print ('Variable as raw data = %r' %(var)) #%i - Integer print('Variable as integer = %i' %(int(var))) #%f - float print('Variable as float = %f' %(float(var))) #%x - hexadecimal print('Variable as hexadecimal = %x'%(int(var))) #%o - octal print('Variable as octal = %o' %(int(var)))
Variable as string = 27 Variable as raw data = '27' Variable as integer = 27 Variable as float = 27.000000 Variable as hexadecimal = 1b Variable as octal = 33