Summary of string formatting methods in Python, and summary in python

Source: Internet
Author: User

Summary of string formatting methods in Python, and summary in python

The str. format function is added to Python2.6 + to replace the original '%' operator. It is more intuitive and flexible than '%. The following describes how to use it in detail.

The following example uses '%:

"""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 similar to that of C-language printf, isn't it? As '%' is an operator, only one parameter can be placed on both sides of the left and right. Therefore, multiple values on the right must be included in tuples or dictionaries. These values cannot be used together with tuples and lack flexibility.

In the same example, use the format method to rewrite:

"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 expression in the previous format when using C language :-))

Format a string

"{named} consist of intermingled character {0} and {1}".format("data", "markup", \  named = "Formats trings")format(10.0, "7.3g") # => '   10'"My name is {0} :-{{}}".format('Fred') # => 'My name is Fred :-{}'

Note the '\' of the first line. To wrap a statement, you must add a backslash to the end.

'%' Cannot be used to mix tuples and dictionaries like this. In fact, this is a named parameter, a feature of Python. You can use the * args and ** kwargs syntax to expand the set and dictionary when defining arrays. Note that the named parameters are placed behind them.

The second statement indicates that the format built-in function is used to format a single value.

The third statement represents the escape of {}, because {} is a special character in the formatted string and cannot be directly displayed. The escape method is to nest multiple layers.

Use attributes and Indexes

"My name is {0.name}".format(open('out.txt', 'w')) # => 'My name is out.txt'

'{0. name}' is equivalent to open('out.txt ', 'w'). name

"My name is {0[name]}".format(dict(name='Fred')) # => 'My name is Fred'

You can also use indexes.

Obj [key] is equivalent to obj. ____ getitem ____ ('key ')

Standard Specifiers)

Programmers who have written C language should understand the complexity of printf. Format also defines many standard specifiers to explain the format of a value and insert it into the string. For example:

"My name is {0:8}".format('Fred') # => 'My name is Fred  '

':' Is followed by a description. In the preceding example, there is only one '8' (minimumwidth), which indicates that the inserted value is at least 8 in width. 'Fred 'has only four spaces.

The detailed format of the specifier is:

[[fill]align][sign][#][0][minimumwidth][.precision][type](No more concise than C's printf !)

Note: '[]' indicates that this element is optional. Therefore, all format specifiers are optional! As in the previous example, this is almost useless (just to make the example clearer ). In fact, these are very useful.

Let's take a look:
1. [fill] align indicates the arrangement mode. When minimumwidth is set to a larger value than the inserted value, it is left white, just like 'My name is Fred 'in the previous example '. By default, the white space is placed on the right, that is, the inserted value is left aligned by default. If we try {0:> 8}, we will find that the result is 'My name is Fred '.
Fill indicates the characters used to fill the white space. Fill is useful only when align is specified! Align can be the following identifier:

  • <Left alignment, default
  • > Right alignment
  • = Put the white space behind the align identifier, which is only valid for numbers. What does it mean? As described in align, displaying positive and negative numbers is also only valid for numbers. If '=' is specified, the positive and negative numbers are displayed before the white. For example, format (-12, "0 = 8") # => '-0000012'. Note that the built-in Function format for formatting a single value is used here. '0' is the fill element, which is used to fill the white space; '=' is the identifier; '8' is the minimum width of 8, so there are 5 white spaces. What about align? Align is actually the display method of the positive and negative signs. Here we use the default '-', which will be discussed later.
  • ^ Center alignment

2. The sign is only valid for numbers.

  • + The plus and minus signs are displayed.
  • -If the plus sign is not displayed, the minus sign is displayed. If the minimum width is not specified, the negative number always occupies a symbol position more than the positive number. Default
  • ''(A space) replaces the plus sign with a white space

3. # indicates the number prefix (0b, 0o, 0x)

4. Fill 0 with '0' for white.

5. minimumwidth specifies the minimum width, which has been used many times.

6. precision 'precision 'is a decimal number that indicates the number of digits after the decimal point.

7. type of the type value:

① INTEGER:

  • B binary
  • Converts a number to a unicode character.
  • D decimal
  • O octal
  • X hexadecimal format: lowercase letters
  • X hexadecimal format, with uppercase letters displayed
  • The behavior of n is the same as that of d. It is represented by a local number.
  • ''(Null, no space) is the same as d

② Floating point number

  • E scientific notation, lowercase e
  • E scientific notation, Capital E
  • F is displayed as the number of points. The default value is six digits after the decimal point.
  • F is the same as f
  • G automatically selects whether to use scientific notation
  • G same as g
  • N is the same as g, using local representation
  • % Indicates percentage
  • ''(Null) Same as g

Each object can override its own formatting specifiers. For example, after the datatime class is rewritten, it can be expressed as follows:

"Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())

Pre-Conversion

':' Is followed by a format specifier. You can add a pre-converted identifier before.

  • ! R calls the _ repr _ method of the object to convert it into a standard string.
  • ! S calls the _ str _ method of the object to convert it into a string.

Override _ format _ Method

When formatting a string, we first format each value and then insert it into the string. The format value calls the format built-in method. Format is to call the _ format _ method of this value.

def format(value, format_spec):  return value.__format__(format_spec)

The _ format method is implemented in the object class, but the str () method is used to convert itself into a string, and then the string is passed into the built-in format method, actually, it is to call the format _ method after conversion to a string.

class object:  def __format__(self, format_spec):    return format(str(self), format_spec)

Int/float/str implements the _ format _ method. Their Respective specifiers have been described earlier.

Conclusion

There is also a custom Formatter, but it is not commonly used. Let's take a look at the source code of the string module. If you are interested, please read the source code of the Python standard library, which is of great learning value.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.