From Python 3.6 onwards, you can use an Formatting string literal (aka f-strings), which takes any valid Python expression inside {...}
curly braces, followed by optional formatting instructions:
print(f'Hi, my name is {name} and my age is {age:d}')
Here name
and age
are both simple expressions that produce the value for that name.
In versions preceding Python 3.6, you can use str.format()
, paired with either locals()
or globals()
:
print('Hi, my name is {name} and my age is {age}'.format(**locals()))
As you can see the format is rather close to Ruby's. The locals()
and globals()
methods return namespaces as a dictionary, and the **
keyword argument splash syntax make it possible for the str.format()
call to access all names in the given namespace.
Demo:
>>> name = 'Martijn'
>>> age = 40
>>> print('Hi, my name is {name} and my age is {age}'.format(**locals()))
Hi, my name is Martijn and my age is 40
Note however that explicit is better than implicit and you should really pass in name
and age
as arguments:
print('Hi, my name is {name} and my age is {age}'.format(name=name, age=age)
or use positional arguments:
print('Hi, my name is {} and my age is {}'.format(name, age))