String Formatting in Python using %?



We can easily format a string in Python using %. Following are the Formatters −

  • Integer − %d
  • Float − %f
  • String − %s
  • Hexadecimal − %x
  • Octal − %o

Formatting String Variable as integer

To format string variable as an integer, use the int() method and set the string as a parameter −

Example

# string var = '12' #%i - Integer print('Variable as integer = %i' %(int(var)))

Output

Variable as integer = 12

Formatting String Variable as float

To format string variable as a float, use the float() method and set the string as a parameter −

Example

# string var = '12' #%f - float print('Variable as float = %f' %(float(var)))

Output

Variable as float = 12.000000

Formatting String Variable as Hexadecimal

To format string variable as Hexadecimal, use the int() method and set the string as a parameter. For hexa, use %x'% −

Example

# string var = '12' #%x - hexadecimal print('Variable as hexadecimal = %x'%(int(var)))

Output

Variable as hexadecimal = c

Formatting String Variable as Octal

To format string variable as an Octal, use the int() method and set the string as a parameter. For hexa, use %o' % −

Example

# string var = '25' #%o - octal print('Variable as octal = %o' %(int(var)))

Output

Variable as octal = 31

Advertisements