English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Python2.6+ The str.format function has been added to replace the original '%' operator. It is more intuitive and flexible than '%'. Let's introduce its usage in detail.
Here is an example using '%':
"" "PI is %f..." % 3.14159 # => 'PI is 3.141590... "%d + %d = %d" % (5, 6, 5+6) # => '"5 + 6 = 11" "The usage of %(language)s" % {"language": "python"} # => 'The usage of python'
The format is very similar to C language's printf? Since '%' is an operator, it can only be placed on both sides of one parameter, so multiple values on the right need to be enclosed in a tuple or dictionary, and cannot be used together with both, lacking flexibility.
The same example rewritten using the format method:
"PI is {0}...".format(3.14159) # => 'PI is 3.14159..." "{0} + {1}) = {2").format(5, 6, 5+6) # => '"5 + 6 = 11" "The usage of {language}".format(language = "Python") # => 'The usage of Python'
Is it intuitive? (Of course, I also like the first format expression method used in C language :)-) )
Formatting strings
"{named} consist of intermingled character {0} and {1").format("data", "markup", \ named = "Formats trings" format(10.0, "7.3g") # => '" 10" "My name is {0} :"-Formatting a string with 'Fred' # => 'My name is Fred :'-{}'
Note the first line '\', if a statement needs to be wrapped, a backslash escape must be added at the end.
The '%' symbol cannot be used to mix tuples and dictionaries as shown here. In fact, this is named arguments, a feature of Python. You can use*args, **kwargs syntax expands collections and dictionaries. Note that named arguments are placed at the end.
The second statement indicates that the format built-in function is used to format a single value.
The third statement indicates the escaping of {}, because {} is a special character in a formatted string and cannot be displayed directly. The escaping method is to add an additional layer of nesting.
Using properties and indices
"My name is {0.name}".format(open('out.txt', 'w')) # => 'My name is out.txt'
'{0.name}' is equivalent to calling the object's property open('out.txt', 'w').name
"My name is {0[name]}".format(dict(name='Fred')) # => 'My name is Fred'
Using an index is also possible.
obj[key] is equivalent to obj.__getitem__('key')
Standard Specifiers (Specifiers)
Programmers who have written C should be familiar with the complexity of printf. format also defines many standard specifiers to explain the format of a value and then insert it into a string. For example:
"My name is {0:8'.format('Fred') # => 'My name is Fred '
':' followed by the specifier, as shown in the previous example with only one specifier single quote'8'(minimumwidth)', which indicates that the width of the inserted value must be at least8. 'Fred' only has4Therefore, another one was added4spaces.
The detailed format of the specifier is:
[[fill]align][sign][#][0][minimumwidth][.precision][type] (not more concise than C's printf!)
Note: '[]' indicates that the element is optional. Therefore, all format specifiers are optional! As in the previous examples, this is rarely used (just to make the example clearer). In fact, they are very useful.
Let's take a look one by one:
1The 'align' parameter indicates the alignment method. When the 'minimumwidth' is set larger than the inserted value, there is space left, as shown in the previous example with 'My name is Fred '. By default, the space is placed on the right, which means the inserted value is aligned to the left by default. If we try {0:>8}
fill Indicates the character used to fill the blank. fill is only useful when align is specified! align can be the following identifiers:
2、sign Digital sign, valid only for numbers.
3、# Displays the prefix indicating the number base (0b, 0o, 0x)
4、0 Fills the blank with '0'.
5、minimumwidth Specifies the minimum width, which has been used many times.
6、.precision 'precision' is a decimal number indicating the number of decimal places to display.
7、type The type of the value
①Integer type:
②Floating point number
Each object can overwrite its own format specifiers, for example, the datetime class can be rewritten as follows:
"Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())
Pre-converted
The symbol ':' is followed by the format specifier, and can be preceded by a pre-converted identifier
Override the _format_ method
When formatting a string, we first format each value and then insert it into the string. The formatting of the value calls the built-in format method. format simply calls the _format_ method of the value.
def format(value, format_spec): return value.__format__(format_spec)
The _format method is implemented within the object class, which simply converts itself to a string using str() and then passes the string to the built-in format method, which is actually calling the _format_ method after conversion to a string.
class object: def __format__(self, format_spec): return format(str(self), format_spec)
int/float/str itself implements the _format_ method, and the descriptions of their respective specifiers have been introduced before.
Closing Remarks
There is also a little bit about custom Formatter, which is not often used. It is left for the next article on the source code interpretation of the string module. It is recommended that friends with interest read more Python standard library source code, which is very valuable for learning.
That's all for this article, I hope it will be helpful to your learning, and I also hope everyone will support the Yell Tutorial.
Statement: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo artificial editing, and does not assume relevant legal liabilities. If you find any copyright-infringing content, please send an email to: notice#oldtoolbag.com (When reporting, please replace # with @ and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)