logo

How to Interpolate Strings in Python 📂Programing

How to Interpolate Strings in Python

f-string

f-strings can be used from Python 3.6 and are the simplest and most convenient method of string interpolation. By prefixing the string with an f and using variables within the string as {variable}, you can achieve this.

>>> name = 'An, Yujin'
>>> birthday = '2003'
>>>
>>> print(f'The leader of IVE is {name}, and she was born in {birthday}.')
The leader of IVE is An, Yujin, and she was born in 2003.

str.format()

You can interpolate using the .format() method on strings. It significantly lacks readability compared to the f-string method. The variable placeholders are left as empty curly braces {}, and then arguments are passed in order into the method.

>>> name = 'An, Yujin'
>>> birthday = '2003'
>>>
>>> print('The leader of IVE is {}, and she was born in {}.'.format(name, birthday))
The leader of IVE is An, Yujin, and she was born in 2003.
>>>
>>> print('The leader of IVE is {name}, and she was born in {birthday}.'.format(name='An, Yujin', birthday='2003'))
The leader of IVE is An, Yujin, and she was born in 2003.

C-style interpolation

You can use % for interpolation as follows.

>>> print('The leader of IVE is %s, and she was born in %d.' % ('An, Yujin', 2003))
The leader of IVE is An, Yujin, and she was born in 2003.

Template

The Template class from the string module can be used for interpolation.

>>> from string import Template
>>>
>>> template = Template("The leader of IVE is $name, and she was born in $birthday.")
>>> str = template.substitute(name='An, Yujin', birthday=2003)
>>> print(str)
The leader of IVE is An, Yujin, and she was born in 2003.

Environment

  • OS: Windows11
  • Version: Python 3.11.5