The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4
since 34 divided by 10 is three, with a remainder of four.
If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example:
>>> "foo %d bar" % 5
'foo 5 bar'
However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format()
mechanism:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format()
interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
And thankfully, almost all of the new features are also available from python 2.6 onwards.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…