Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
George John

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.