string formatting of Python

Source: Internet
Author: User
Tags format definition string format

1. What kinds of string formatting modules does Python have?

Python has 3 ways to format strings:

    • The traditional% string format character
    • Str.format function
    • String Template Template

The new Python 3.6+ also provides a new F modifier

2. Traditional% string format character

Python uses a string format output similar to the use of sprintf in the C language. The string object has a unique built-in operation:% operator. This is also known as string formatting or interpolation operators. Given the format% value (where format is a string), the conversion specification replaces the format% with 0 or more element values.

'%[[(key)][flag][width][.precision]]type '% (Key list)

If the format is a single parameter, the key can be a single non-tuple object: '%s '%key. Otherwise, the value must be a tuple with the number of items specified by the format string, or a single mapping object (for example, a dictionary).

Flag can be #, 0,-, space, or +:

Flag Meaning # The value conversion would use the ' alternate form"'(wheredefined below).0The conversion would be zero padded fornumeric values.-The converted Value isLeft adjusted (Overrides the"0"Conversionifboth is given). (a space) A blank should is left before a positive number (or emptystring) produced by a signed conversion.+ A Sign character ("+"Or"-") would precede the conversion (Overrides a"Space"Flag).

The type can be defined in the following different types:

type meaning comment D signed integerdecimal. I signed integerdecimal.             o Unsigned octal. (1) u Unsigneddecimal.  x Unsigned hexadecimal (lowercase). (2) X Unsigned hexadecimal (uppercase). (2) e floating point exponential format (lowercase).    E floating point exponential format (uppercase). F Floating Pointdecimalformat. F Floating Pointdecimalformat. G Same as "e" ifExponent isGreater than-4or less than precision,"F"otherwise. G same as "E" ifExponent isGreater than-4or less than precision,"F"otherwise. C single character (accepts integer or single characterstring). R String (converts any PythonObject usingRepr ()). (3) s String (converts any PythonObject usingSTR ()). (4)% No argument isConverted, resultsinchA"%"CharacterinchThe result.

Like what:

    • >>> '% (name) s GPA is% (#) 07.3f '%{' name ': ' Yue ', ' # ': 88.2}
      ' Yue GPA is 088.200 '

    • >>> '% (name) 10s GPA is% (#) 7.2f '%{' name ': ' June ', ' # ': 89.1299}
      ' June GPA is 89.13 '

3. Str.format function

PEP 3101 Specifies the standard for formatting strings using the Str.format () function. Syntax for Str.format ():

‘... {Replacement_field} ... '. Format (*arg, **kargs)

The specific explanations are as follows:

Replacement_field:: ="{"[Field_name] ["!"Conversion] [":"FORMAT_SPEC]"}"field_name::= Arg_name ("."Attribute_name |"["Element_index"]")*arg_name::= [Identifier |integer]attribute_name::=Identifierelement_index::= Integer |index_stringindex_string::= <any source character except"]"> +Conversion::="R"|"s"Format_spec::= <describedinchThe next section>

Example:

>>>'Bring {0} a {1}'. Format ('Me','Apple'# and C # a bit like, numbers represent locations'Bring me a apple'>>>'Bring {} a {}'. Format ('Me','Apple') 'Bring me a apple'>>>'Bring {name} a {fruit}'. Format (fruit='Me', name='Apple')'bring Apple a me'

Here is the definition of Format_spec:

Format_spec:: = [[fill]align][sign][#][0][width][,][.precision][type]fill::= <any character>align::="<"|">"|"="|"^"Sign ::="+"|"-"|" "Width::=integerprecision::=Integertype::="b"|"C"|"D"|"e"|"E"|"F"|"F"|"g"|"G"|"N"|"o"|"s"|"x"|"X"|"%"

Sometimes, further customization is required, and the formatter class in the string module needs to be used to customize the format.Formatter类有以下公共函数:

    • format(format_string, *args, **kwargs): It calls the following Vformat function.
    • vformat(format_string, args, kwargs): produces the corresponding string based on arguments and formatting strings. It calls the following functions that can be overloaded.

In addition, the Formatter class defines some other functions that can be overloaded:

  • parse(format_string): Decomposition of the format definition format_string;
  • get_field(field_name, args, kwargs): Produces a formatted object for a field based on the output of Parse ();
  • get_value(key, args, kwargs): Gets the value of a field;
  • check_unused_args(Used_args, args, kwargs)
  • format_field(value, format_spec)
  • convert_field(value, conversion)
4. String template Template

The template supports replacement based on $ instead of the normal%-based substitution:

    • $$ is used to replace $.
    • $ identifier name matches the replacement placeholder for the mapping keyword "identifier". By default, "identifier" must spell the python identifier. The first non-identifier character after the $ character terminates this placeholder specification.
    • $ {identifier} is equivalent to $ identifier. This is required when a valid identifier character follows a placeholder but is not part of a placeholder, such as "$ {noun} ification".
    • The occurrence of $ in a string anywhere else will result in a ValueError exception.

Example:

>>> from stringImport Template>>> S1 = Template ('Today is $weekday, it is $weather')>>> S1.substitute (Weekday ='Tuesday', weather ='Sunny')'Today is Tuesday, it is sunny'>>> S1.substitute (Weekday ='Tuesday')... Keyerror:'Weather'>>> S1.safe_substitute (Weekday ='Tuesday')'Today is Tuesday, it is $weather'>>> s2 = Template ('$fruit is $2.99 per pound')>>> S2.substitute (fruit ='Apple')...Valueerror:invalid Placeholderinch string: Line1, col One>>> s2 = Template ('$fruit is $$2.99 per pound')>>> S2.substitute (fruit ='Apple')'Apple is $2.99 per pound'
References:

[1] https://docs.python.org/2/library/stdtypes.html#string-formatting

[2] Https://docs.python.org/2/library/string.html

string formatting of Python

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.