What does % do to strings in Python?

% is a string formatting operator or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language. For example,

>>> lang = "Python"
>>> print "%s is awesome!" % lang
Python is awesome

You can also format numbers with this notation. For example,

>>> cost = 128.527
>>> print "The book costs $%.2f at the bookstore" % cost
The book costs $128.53 at the bookstore

You can also use dictionaries to interpolate strings. They have a syntax in which you need to provide the key in the parentheses between the % and the conversion character. For example,

print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.

You can read up more about string formatting and their operators here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

Updated on: 30-Sep-2019


Kickstart Your Career

Get certified by completing the course

Get Started