English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of Methods for String Formatting in Python

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:

  •  < Left-aligned, default
  • > Right-aligned
  • = Places the blank after the align identifier, valid only for numbers. What does this mean? The align will be discussed later, displaying the positive and negative signs of numbers, which are also valid only for numbers. If '=' is specified, then the positive and negative signs of the number will be displayed in front of the blank. For example: format(-12, "0="8) # => '-0000012‘Note that here we use the built-in function format for formatting a single value. '0' is the fill element, used to fill the blank; '=' is the identifier; '8‘ means the minimum width is8,therefore there is5a blank. So what is align? Align is actually an explanation of the display method of the positive and negative signs, here using the default '-,which will be discussed later.
  • ^ Center-aligned

2、sign Digital sign, valid only for numbers.

  • + Displays both plus and minus signs
  • - The plus sign is not displayed, and the minus sign is displayed. Without specifying the minimum width, negative numbers always occupy one more symbol position than positive numbers. Default
  • ' ' (a space) replaces a plus sign with a blank

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:

  •  b Binary
  • c Character type, converts numbers into Unicode characters
  • d Decimal
  • o Octal
  • x Hexadecimal, displaying lowercase letters
  • X Hexadecimal, displaying uppercase letters
  • n is the same as d, using the local number representation
  • ''(empty, no space) is the same as d

②Floating point number

  • e represents in scientific notation, lowercase e
  • E represents in scientific notation, uppercase E
  • f displays as a fixed-point number, with a default of six decimal places
  • F is the same as f
  • g automatically chooses whether to represent in scientific notation
  • G is the same as g
  • n is the same as g, using the local representation method
  • % is used to represent percentages
  • ''(empty) is the same as g

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

  • !r calls the _repr_ method of the object to convert it to a standard string
  • !s calls the _str_ method of the object to convert it to a string

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.)

You May Also Like