Qianjiang Hu
2022-04-16
name = 'QJ'
age = 16
% Operator
¶%d
will truncate to integer, %s
will maintain formatting, %f
will print as float and %g
is used for generic number
%x
format specifier convert an int value to a string and represent it as a hexadecimal number
'Hello, this is %s; I am %d years old' %(name, age)
'Hello, this is QJ; I am 16 years old'
name ='QJ'
number = 16.6
print('QJ is printing: %s (str) %s (str) %d (integer) %f (float) %g (generic number)' % (name, number, number, number, number))
QJ is printing: QJ (str) 16.6 (str) 16 (integer) 16.600000 (float) 16.6 (generic number)
It’s also possible to refer to variable substitutions by name if passing a mapping to the %
operator
'Hey, this is %(name)s; I am %(age)d years old!' % {"name": name, "age": age}
'Hey, this is QJ; I am 16 years old!'
'{}'.format()
¶name = 'QJ'
age = 16
'Hey, {name}, are you {age} years old?'.format(name=name, age = age)
'Hey, QJ, are you 16 years old?'
f'{}'
f'Hey, {name}, are you {age} years old?'
'Hey, QJ, are you 16 years old?'
a = 5
b = 10
f'Five plus ten is {a + b} and not {2 * (a + b)}.'
'Five plus ten is 15 and not 30.'
def selfintro(name, age):
return f"Hello, {name} is {age} years old?"
selfintro('QJ', '16')
'Hello, QJ is 16 years old?'
from string import Template
t = Template('Hey, $name!')
t.substitute(name=name)
'Hey, QJ!'
sample = 'Hey $name, I am $age years old!'
Template(sample).substitute(name=name, age = age)
'Hey QJ, I am 16 years old!'