I have failed to find documentation for the operator % as it is used on strings in Python. What does this operator do when it is used with a string on the left hand side?
Asked
Active
Viewed 4.4k times
4 Answers
40
It's the string formatting operator. Read up on string formatting in Python.
format % values
Creates a string where format
specifies a format and values
are the values to be filled in.

phyatt
- 18,472
- 5
- 61
- 80

Konrad Rudolph
- 530,221
- 131
- 937
- 1,214
10
It applies printf-like formatting to a string, so that you can substitute certain parts of a string with values of variables. Example
# assuming numFiles is an int variable
print "Found %d files" % (numFiles, )
See the link provided by Konrad

Diaa Sami
- 3,249
- 24
- 31
8
Note that starting from Python 2.6, it's recommended to use the new str.format()
method:
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
If you are using 2.6, you may want to keep using %
in order to remain compatible with older versions, but in Python 3 there's no reason not to use str.format()
.

Bastien Léonard
- 60,478
- 20
- 78
- 95
-
3format() is really powerful too. You can use named tags like "Hello {planet}".format(planet='earth') – aehlke Aug 06 '09 at 14:27
-
what does the 0 inside the {} do? this line of code seemingly runs the same without it – Wizard Apr 29 '21 at 19:15
6
The '%' operator is used for string interpolation. Since Python 2.6 the String method "format" is used insted. For details see http://www.python.org/dev/peps/pep-3101/