String Formatting in Python using %?

PythonServer Side ProgrammingProgramming

In python, a string can be formatted using different methods, like −

  • Using %
  • Using {}
  • Using Template String

And we are going to discuss the “%” string formatting option in this section.

String formatting comes in two flavors−

  • String formatting expression: Based on the C type printf
  • String formatting method calls: This option is available in python 2.6 or higher.

Formatting using % comes from the C type printf and support following types

  • Integer - %d
  • Float - %f
  • String - %s
  • Hexadecimal - %x
  • Octal - %o
>>> 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)))

output

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
raja
Published on 02-May-2019 11:35:57
Advertisements