String Formatting
Types
- s – sring
- d – decimal
- f – float
- .2f – float with 2 decimal
Old Method – Example¶
%s
Passing one parameter
Passing more than one parameter
In [55]:
x='Raj' #string - %s
y='Ravi'
text1='the variable is %s' %x #passing one parameter
text2='the variable is %s and %s' %(y, x) #Passing More than one Parameter
print(text1)
print(text2)
the variable is Raj the variable is Ravi and Raj
In [49]:
var1 = 10 #decimal %d
var2 = 3.1234 #float %f or %.2f
text = 'the value of var1 is %d and the value of var2 is %.2f. Note var2 is rounded to two decimal' %(var1,var2)
print(text)
the value of var1 is 10 and the value of var2 is 3.12. Note var2 is rounded to two decimal
New Method – Example¶
{} and .format
Passing one parameter
Passing more than one parameter
In [54]:
x='Raj' #string - %s
y='Ravi'
text1 = 'the variable is {}'.format(x) #passing one parameter
text2 = 'the variable is {} and {}' .format(y, x) #Passing More than one Parameter.
print(text1)
print(text2)
# Some flexibility there in .format method where we don't have to mention the type like %s or %d or %f
the variable is Raj the variable is Ravi and Raj
Another New Method – Example¶
f-string method
In [56]:
x='Raj' #string - %s
y='Ravi'
text1 = f'the variable is {x}' #passing one parameter
text2 = f'the variable is {y} and {x}' #Passing More than one Parameter.
print(text1)
print(text2)
# f-string method is easy to use method
the variable is Raj the variable is Ravi and Raj
In [69]:
# Using .format method with positional argument - passing variable value through function return value
def test():
print('Ravi-Raju')
return 'aju'
print('R{0}-{1}{0}'.format(test(), 'R'))
Ravi-Raju Raju-Raju