Section 3.11 Python string formatting powerful new features: format format control string formatting

Original link: http://www.cnblogs.com/LaoYuanPython/p/11087732.html

                                            Section 3.11 format formatted string format control
I. Introduction
upper section describes four methods formatted string format, but only describes the relationship between the true value and the location mapping format breaks, but does not describe such a width, alignment, precision control of each real value to control the display content format. This section describes how to control the format of the formatted string, the control elements of this format is called a "format specifier" format in the formatting.
Described in the previous section "format characters" (also referred to as "substitution field", "conversion specifier"), it is a sub-format specifier character string format, designed to control the output format.

Second, the content formatter
in formatting string format, the content "specifier" in the braces (brace is placeholder), and in the following composition:
specifier: {[Field Name] [[conversion flag!] : format specifier]}
1. field name: index or identifier, can be digital (i.e. an index), variable, variable attributes, variables [index], the variable [key], which indicated the true value to be set and use the results. to replace the field. See Case part;
2. Switch Flag: a single character followed exclamation mark. R & lt currently supports characters (represented repr), s (expressed str) and a (expressed ascii). If you specify a conversion flag is not used formatting mechanism object itself, but the use of the specified function to convert the object to a string, do further formatting. The three flag (s, r and a) are designated using str, repr and ascii conversion. About three types, old ape no in-depth research, we have come to: s = '20190301 class Xiaoming students, nickname: Xiao Ming, Total: 597.5' string to test:
1) ASCII (S) Output: With double quotes code string
" '20190301 \\ u73ed \\ u5c0f \\ u660e \\ u540c \\ u5b66, \\ u5c0f \\ u540d \\ uff1a \\ u5c0f \\ u660e \\ uff0c \\ u603b \\ u5206: 597.5 ' "
2) the repr (s) output: input before the original double-quoted
"' 20190301 Xiaoming class students, nickname: Xiaoming, Total: 597.5 ''
. 3) STR (s): the same as the value of s.
Str function normally create the appearance of a normal version string (do not do any processing of the input string). Repr function tries to create a given value of the Python representation (here is a string literal, old ape temporarily do not understand this sentence, the contents of memory may be stored in a string in Python?). Create a function ascii representation contains only ASCII characters (old ape character is not understood is to convert ascii code to show double-byte coding).

3. The format specifier: specifies the language expression with miniature format after the colon. Let us format specifier specify the detail of the final format, including the format type (e.g., string, floating point, or hexadecimal number), and number of field width accuracy, and how to display the symbol thousand separator, and a variety of alignment and filling mode.
Syntax: [[Filler] alignment] [symbol] [#] [0] [width] [grouping options] [accuracy.] [Type]
1) all format specifier fields are optional;
2) Filler: can be any characters, it will display the contents of the set width than the width of the short padded with fILLER;
3) alignment: "<" symbol indicates left, ">" represents a right alignment, "^" is centered " = "is used for signed digital alignment between symbols and numerals added filler, when filler is not specified, the default padding (space), but if the width of the front numbers 0, 0 replaces the default filler.
About equal sign digital alignment example:
'{:}. 9 = +'. The format (12345) # results: '12345 +'
'{:} 09 = +'. The format (12345) # results: '+ 00012345 '
' {:} * = + 09 '. the format (12345) # results:' 12345 + *** '
4) symbols: for digital only, "+" before the number represents positive and negative signs plus, "-" indicates only negative plus negative sign, which is the default mode, the space represents a space before positive numbers, plus a minus sign before negative number
5) #: indication "alternatives" when converted to a string. This option is available only integer, float, complex and decimal types. For integer, using binary, octal or hexadecimal output, this option adds the prefix "0b", "0o" or "0x" are added to the output value. For floating-point numbers, complex numbers and decimals, alternative forms will lead to the conversion result (even if no numbers behind) always contain a decimal point character. In addition, "g" and "g" conversion, trailing zeros are not removed from the results.
6) 0: When not specified filler, if there is a "0" before the width of the figures, "0" replaces the default padding;
7) Width: data output occupied width, actual when the actual output is greater than the width width of the output at this time has no effect alignment and padding;
8) group options: for digital "," option represents a comma is used as the thousands separator. "_" Option indicates the type of floating-point and integer representation type "d" of the thousands separator with an underscore. For integer type "B", "O", "X" and "x", underline inserted every four. For other types, this option is specified error;
9) Accuracy: precision floating point value for the format of "f" and "F", and indicates how many digits after the decimal point to be displayed, the format for the "g" or "G" the floating-point values, the number of digits before and after the decimal point should be displayed. For non-numeric type, a field indicating the maximum field size - in other words, the accuracy is less than the string length of the string, in front of the direct intercept length. Integer values allowed precision. To little attention before precision.
10) Type: Description Type true value of
type Meaning
b integer represented as a binary number
c interpreted as integer Unicode code point
d to be decimal integer processing, which is described using the default symbol integer
e Use scientific notation to representing the fraction (expressed by index e)
E E and the same, but the index represented by E
f is the fixed decimal point
F and f the same, but for a special value (NaN3 and INF), uppercase represents
g automatically fixed-point notation and scientific method to choose between representation. The default for decimal, with at least one fractional default
G and g are the same, but the use of capital to represent the exponent and special values
n and d are the same, but the insert with the region-specific number separators
o integer represented as octal
s remains unchanged string format, which is the default for the specifier string
x represents an integer hexadecimal lowercase letters and
X are the same as x, except that capital letters
% expressed as a percentage value of the number of ( multiplied by 100, according to f format specifier, and then followed by the%)
when None when no type is specified, the string in the s manner, a digital manner by d, g floating manner by
three formatter example
student = { ' name ':' Bob ',' class ':' 20,190,301 ',' score ': 597.5}
1. S1 =' {ST [class]} class {st [name]: _> 4} Total: {st [score ]: 0> + 6.1f} ' format (st = student).
results of: s1 =' 20190301 ban __ Xiaoming out: +597.5 '
2. s2 = '{st [class ]} class {st [name] r:! _> 4} Total: {st [score]: 0 > + 6.1f}'. Format (st = student)
specifies the name conversion labeled r, the execution result: s2 = "20190301 ban 'Bob' Total: +597.5"
3. S3 = F "Student {[ 'classno']} class {student [ 'name']: _> 4} out : {student [ 'score'] : 0> + 6.1f} "
the results: '20190301 ban __ Xiaoming out: +597.5', the dictionary key note here the single quotation marks added.
4. '{: *> + # 10 _}'. Format (123456) # result '** + 123_456'
5. The '{: *> + # 10_b}' the format (123456) # result '+ 0b1_1110_0010_0100_0000'.
6. '{: *> + # 10_o}'. format (123456) # result '+ 0o36_1100
7. The' {: *> *} + + # 10_x 0x1_e240 '' the format (123456) # result. '

The above example is not additional explanation, we explain himself in front of the control analysis.

This section details the composition of the format string format characters and meanings of each part, and an example is described, more content, not easy to remember, let us first understand, carry out the specific information Quick format on actual use it. Finally add introduce several modules string constants and string associated with a function:
string.digits: comprising a string of numbers 0-9.
string.ascii_letters: a string containing all ASCII letters (uppercase and lowercase) of.
string.ascii_lowercase: include all lower-case letters ASCII string.
string.printable: a string containing all the printable ASCII characters.
string.punctuation: a string containing all ASCII punctuation characters.
string.ascii_uppercase: contains all uppercase letters ASCII string. Although the ASCII characters, but the value is not actually decode Unicode strings.
string.capwords (s [, sep]) using the split according to the split sep s, each of the first letter capitalized, then a delimiter SPLIT combining them, such as:
string.capwords (s, '/')
' / Usr / Var / Tempdirectory '
until this section describes the contents of a string of six total content, basically a string of related content on the whole introduction is over, I hope we have a good understanding.


As of this section, the basics of Python data types on the introduction finished. This time around the old ape is to write at least one blog every day, are sorted out based on the contents of the knowledge base on early learning, preparing generators, iterators described later in this post, and so part of the list comprehension also in-depth study and summarize, behind the update will slow down, but at least guarantee a weekly update of content, while personally think that behind these contents belong to advanced content data type, will open a new chapter introduced.

    Old ape Python ( https://blog.csdn.net/LaoYuanPython ) series of articles for the gradual introduction summary of the old ape learning Python learning experience, which helps no contact with Python programmers can easily enter Python world. 
    Welcome criticism, thank you attention!

Reproduced in: https: //www.cnblogs.com/LaoYuanPython/p/11087732.html

Guess you like

Origin blog.csdn.net/weixin_30642561/article/details/95152405