Python format string format

Author: Tyan Blog: noahsnail.com | CSDN | A brief book 0. Test environment Python 3.6.9 1. Introduction There are tw...
0. Test environment
1. Introduction
2. Format string
References

Author: Tyan
Blog: noahsnail.com | CSDN | A brief book

0. Test environment

Python 3.6.9

1. Introduction

There are two ways to format strings in Python: one is to format strings with the% operator, and the other is to use the str.format() for string formatting, this article mainly introduces str.format() mode, which is more mainstream and also recommended by the government, will be gradually eliminated later.

2. Format string

2.1 basic grammar

The format string contains the replace field, enclosed in braces {},. Content not contained in braces is treated as normal text and output as is. Note: if you want to output braces in the text, you need to use {} to escape, not the escape character \, of the scene. An example is as follows:

>>> 'This is a format {}.'.format('test') 'This is a format test.' >>> 'This is {{}} test.'.format() 'This is {} test.'

The following is the syntax of "replace field", which will be described in the following examples:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" field_name ::= arg_name ("." attribute_name | "[" element_index "]")* arg_name ::= [identifier | digit+] attribute_name ::= identifier element_index ::= digit+ | index_string index_string ::= <any source character except "]"> + conversion ::= "r" | "s" | "a" format_spec ::= <described in the next section>

2.2 location parameter identifier

In the format string, by default, {} can be without location identifier, that is, '{} {}'. format(a, b) and ' '.format(a, b) are equivalent, but if the location identifier does not appear in the string in the order of parameters, it is necessary to display the location identifier. The sample code is as follows:

>>> ' '.format('one', 'two') 'one two' >>> '{} {}'.format('one', 'two') 'one two' >>> ' '.format('one', 'two') 'two one' >>> ' '.format('one', 'two') 'one two one'

2.3 setting parameters

In the format string, you can use variables, dictionaries, list indexes, class properties, etc. to set parameters. The sample code is as follows:

print('Name: , URL: '.format(name='Tyan', url='http://noahsnail.com')) name = 'Tyan' url = 'http://noahsnail.com' print('Name: {}, URL: {}'.format(name, url)) site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'} print('Name: , URL: '.format(site=site)) print('Name: , URL: '.format(**site)) site = ['Tyan', 'http://noahsnail.com'] print('Name: , URL: '.format(site)) class Test(object): def __init__(self): self.name = 'Tyan' self.url = 'http://noahsnail.com' print('Name: , URL: '.format(Test())) site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'} print('Name: , URL: '.format(**site)) # Output Name: Tyan, URL: http://noahsnail.com Name: Tyan, URL: http://noahsnail.com Name: Tyan, URL: http://noahsnail.com Name: Tyan, URL: http://noahsnail.com Name: Tyan, URL: http://noahsnail.com Name: Tyan, URL: http://noahsnail.com Name: Tyan, URL: http://noahsnail.com

2.3 conversion flag

The conversion flag starts with! And there are three types of! s,! r,! a, which call the__ str__ ,__ repr__ ,__ ascii__ method.

class Test(object): def __str__(self): return 'Test str function.' def __repr__(self): return 'Test repr function.' def __ascii__(self): return 'Test ascii function.' print('str: , repr: , ascii: '.format(t=Test())) # Ouput str: Test str function., repr: Test repr function., ascii: Test repr function.

2.4 format_spec)

The format description contains the description of the value representation, including the field width, its method, filling, decimal accuracy, etc., which starts with. The general form of the standard format specifier is:

format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type] fill ::= <any character> align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::= digit+ grouping_option ::= "_" | "," precision ::= digit+ type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
  • < indicates left alignment of output, > indicates right alignment, ^ indicates center alignment, = indicates that the fill value precedes the number after the symbol, for example, + 00001234.
  • +Indicates that both positive and negative numbers need to be signed, - indicates that only negative numbers need to be signed with a negative sign, indicates that a positive number is preceded by a space, and a negative number is preceded by a negative sign.
  • Digital representation. b represents binary format, c represents converting integer to character, D represents decimal integer, o represents octal format, x, X represents hexadecimal format, letters with x greater than 9 are lowercase, and letters with x greater than 9 are uppercase. The default is d.
  • Refer to document [1] for specific explanations of other descriptors.

Examples and results are as follows:

print('{:<8}'.format('1234')) print('{:>8}'.format('1234')) print('{:^8}'.format('1234')) print('{:*>8}'.format('1234')) print('{:*<8}'.format('1234')) print('{:*^8}'.format('1234')) print('{:+f}; {:+f}'.format(3.14, -3.14)) print('{: f}; {: f}'.format(3.14, -3.14)) print('{:-f}; {:-f}'.format(3.14, -3.14)) print('int: ; hex: ; oct: ; bin: '.format(100)) print('int: ; hex: ; oct: ; bin: '.format(100)) print('{:,}'.format(100000000)) print('{:.2e}'.format(100000000)) print('percentage: {:.2%}'.format(1 / 3)) import datetime print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())) # Output 1234 1234 1234 ****1234 1234**** **1234** +3.140000; -3.140000 3.140000; -3.140000 3.140000; -3.140000 int: 100; hex: 64; oct: 144; bin: 1100100 int: 100; hex: 0x64; oct: 0o144; bin: 0b1100100 100,000,000 1.00e+08 percentage: 33.33% 2020-06-18 19:36:38

References

  1. https://docs.python.org/3.8/library/string.html#format-string-syntax

  2. https://www.runoob.com/python/att-string-format.html

  3. https://stackoverflow.com/questions/1436703/difference-between-str-and-repr/1436756

  4. https://stackoverflow.com/questions/9196066/what-does-a-double-colon-followed-by-an-equals-sign-mean-in-programming-do

19 June 2020, 05:15 | Views: 3200

Add new comment

For adding a comment, please log in
or create account

0 comments