2.6. String Formatting
2.6.1. Mod Operator
Since Python 1.0
positional
keyword
%s-str%d-int%f-float
One parameter:
>>> name = 'Alice'
>>>
>>> 'Hello %s' % name
'Hello Alice'
Many parameters as tuple:
>>> firstname = 'Alice'
>>> lastname = 'Apricot'
>>> age = 30
>>>
>>> 'Hello %s %s is %d years old' % (firstname, lastname, age)
'Hello Alice Apricot is 30 years old'
>>> data = ('Alice', 'Apricot', 30)
>>>
>>> 'Hello %s %s is %d years old' % data
'Hello Alice Apricot is 30 years old'
Many parameters as dict:
>>> data = {
... 'firstname': 'Alice',
... 'lastname': 'Apricot',
... 'age': 30,
... }
>>>
>>> 'Hello %(firstname)s %(lastname)s is %(age)d years old' % data
'Hello Alice Apricot is 30 years old'
2.6.2. Format Method
Since Python 3.0
Since Python 3.0: PEP 3101 -- Advanced String Formatting
name = 'Alice'
age = 30
'{} has {} years'.format(name, age) # 'Alice has 30 years'
'{0} has {1} years'.format(name, age) # 'Alice has 30 years'
'{1} has {0} years'.format(name, age) # '30 has Alice years'
name = 'Alice'
age = 30
'{a} has {b} years'.format(a=name, b=age) # 'Alice has 30 years'
'{name} has {age} years'.format(name=name, age=age) # 'Alice has 30 years'
'{age} has {name} years'.format(**locals()) # '30 has Alice years'
2.6.3. f-strings
Since Python 3.6
Preferred way
name = 'Alice'
pi = 3.141592653589793
def square(value):
return value ** 2
f'Hello {name}' # 'Hello Alice'
f'PI squared is {square(pi)}' # 'PI squared is 9.869604401089358'
from datetime import datetime
now = datetime.now()
iso = '%Y-%m-%dT%H:%M:%SZ'
f'Today is: {now:%Y-%m-%d}') # 'Today is: 1969-07-21'
f'Today is: {now:{iso}}') # 'Today is: 1969-07-21T02:56:15Z'