Recently, in the process of learning python, I discovered some situations of % (percent sign). Here is a brief introduction.
The percent sign in Python has two meanings. When calculating numbers, it means finding the remainder; the other one is the format string For example: "%d %s" %(12, 'abc') will replace %d with 12, replace %s with abc, and get '12 abc'. (Recommended learning: Python video tutorial)
The first type: numerical operation 1 % 3 refers to modular operation, taking the remainder (remainder)
>>> 7%2 1
th Two types: String operation 'abc %s' % 'abc' '%s' is similar to placeholder
is asking about the % operator (string formatting), the description is as follows:
%[(name)][flags][width].[precision]typecode
flags can have, -, ' ' or 0.
means right alignment. - means left alignment. ' ' is a space, which means padding a space to the left of the positive number to align it with the negative number. 0 means use 0 padding.
width represents the display width
precision represents the precision after the decimal point
Example
>>> print("%6.3f" % 2.3) 2.300
# The first "% "The following content is the displayed format description, 6 is the display width, 3 is the number of decimal points, f is the floating point number type
# The second "%" is followed by the displayed content source, the output result is right-aligned, and the length is 2.300 It is 5, so there is a space in front
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of What does the percent sign mean in python?. For more information, please follow other related articles on the PHP Chinese website!