Python format() - How to insert values into a string

You can put values into a string in Python.

a = 'I study {} and C++.'.format('math')

print(a)  # I study math and C++.

In this code, the curly brackets are replaced with math. If the format() have two parameters, the original string should have two brackets and the first one is replaced with the first value.

s = '{} is {}'.format('CA', 'California')

print(s)  # CA is California

Substitution order

a = '{0} is {1}'.format('CA', 'California')
b = '{1} is {0}'.format('CA', 'California')

print(a)  # CA is California
print(b)  # California is CA

You can set an index to the curly brackets as above. The brackets with 0 is replaced with the 0th parameter (CA) and the brackets with 1 is replaced with the first parameter (California). The number represents the index of parameters so you can't set 2 to the brackets.

a = 'I study {1} and {2}.'.format('math', 'C++')

# IndexError: Replacement index 2 out of range for positional args tuple


Powered by Markdown