Python ----- format character, python ----- character
Abstract: % s and % r in Python
Python also provides output in a format similar to printf () in C.%Operator, format:
Format mark string % value group to be output
If there are two or more values in the "value group" on the right, they must be enclosed in parentheses and separated by commas.
Focus on the left part. The simplest form is % code. Among them, there can be multiple types of code, and in Python, all input can be converted to the string type, so when there are no special requirements, you can use"% S"Mark.
1 >>>'%s %s %s' % (1,2.3, ['one', 'two', 'three'])
Output:
1 "1 2.3 ['one', 'two', 'three']"2 >>>
The output follows the mark on the left. The first and second are numbers and can also be output. In this process, Python finds that the first value '1' is not of the string type and calls the str () function for output. The second value is output in the same way.
Frequently UsedRepr ()Function, which can be used% RMark. In addition, there are many similar codes:
Integer: % d
Unsigned integer: % u
Octal: % o
Hexadecimal: % x % X
Floating Point: % f
Scientific Notation: % e % E
% E or % f is automatically selected based on different values. Like '/' for escape, '%' is only used for tag format. To output % itself in the format tag, use '%.
1 >>> '%s' %'%1'2 '%1'3 >>>
The following describes several complex examples:
1 >>> '%1.2f' %1.2352 '1.24'3 >>>
The first 1.2 represents: the total output length is 1 character, with two decimal places.
1 >>> '%06.2f' %1.2352 '001.24'3 >>>
% 06.2f indicates that if the number of output digits is less than 6, 0 is used. The decimal point also occupies one character. Similar to-, +,
'-' Indicates the left alignment, and '+' indicates the '+' mark before the certificate. It is not added by default.
1 >>> '%(name)s:%(score)03.1f' %{'score':95, 'name':'Tom'}2 'Tom:95.0'3 >>>
This form only applies when the output content is dictionary (Python is a type of formatted data), the (name) and (score) in the left parentheses correspond to the corresponding content in the subsequent key values.
The preceding example shows that the order marked in the 'format marking string' exactly corresponds to the value of the 'output value group.