Python string formatting

Source: Internet
Author: User

string Formatting

There are two ways to format a python string:% format character, format mode

% Format character

%[(name)][flags][width]. [Precision]typecode

  • (name) optional, used to select the specified key
  • Flags are optional, and the values to choose from are:
    • + Right-aligned, positive plus, negative before plus minus;
    • -left-justified; no sign before positive number, plus minus sign before negative number;
    • Spaces are right-justified, plus a positive number before a negative number plus a minus sign;
    • 0 Right alignment, no sign before positive number, minus sign before negative, and 0 padding in blank
  • Width selectable, occupied widths
  • . Precision optional, number of digits retained after the decimal point
  • TypeCode must choose
    • S, gets the return value of the __str__ method of the passed-in object and formats it to the specified location
    • R, gets the return value of the __repr__ method of the passed-in object and formats it to the specified location
    • C, Integer: Converts a number to its Unicode corresponding value, 10 binary range is 0 <= i <= 1114111 (py27 only supports 0-255); character: add character to specified position
    • O, converts an integer to an octal representation and formats it to a specified location
    • X, converts an integer to a hexadecimal representation and formats it to a specified location
    • D, converts an integer, floating-point number to a decimal representation, and formats it to a specified position
    • E, converting integers, floating-point numbers to scientific notation, and formatting them to a specified location (lowercase e)
    • E, converting integers, floating-point numbers into scientific notation, and formatting them to a specified position (uppercase E)
    • F, converts an integer, floating-point number to a floating-point number representation, and formats it to a specified position (the default is 6 digits after the decimal point)
    • F, ibid.
    • G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
    • G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
    • %, when there is a format flag in the string, a percent sign is required

Note: There is no way to automatically convert an integer to a binary representation in Python with a percent-semicolon format

(name) optional, used to select the specified key

 ""%{' name ': ' xx ', '  age ': 'print(a)

Execution Result:

XX-----20

Flags are optional, and the values to choose from are:

    • + Right-aligned, positive plus, negative before plus minus;
    • -left-justified; no sign before positive number, plus minus sign before negative number;
    • Spaces are right-justified, plus a positive number before a negative number plus a minus sign;
    • 0 Right alignment, no sign before positive number, minus sign before negative, and 0 padding in blank

Width selectable, occupied widths

Name 10-bit, +, right-aligned, age 10-bit,-, left-justified

" % (name) +10s ————————% (age) -10d ————————"%{'name':'xx  'age': 'print' (b)

Execution Result:

        XX ————————        ————————

Spaces, right-aligned

0, fill the blanks with 0

""%{' Year ':, ' age ': -20}  Print(c)

Execution Result:

. Precision optional, number of digits retained after the decimal point

Only two decimal places are reserved

' --------% (p). 2f'%{'P': 1.23456'--------% (P) F  '%{'p': 1.23456}print(d)  Print(D1)

Execution Result:

--------1.23--------1.234560

TypeCode must choose

    • C, Integer: Converts a number to its Unicode corresponding value, 10 binary range is 0 <= i <= 1114111 (py27 only supports 0-255); character: add character to specified position
    • O, converts an integer to an octal representation and formats it to a specified location
    • X, converts an integer to a hexadecimal representation and formats it to a specified location
E ='***%c***%o***%x'% (65,15,15)print(e)

Execution Result:

A***17***f
    • E, converting integers, floating-point numbers to scientific notation, and formatting them to a specified location (lowercase e)
    • E, converting integers, floating-point numbers into scientific notation, and formatting them to a specified position (uppercase E)
' -----% (num) e------% (num) e'%{'num': 1000000000}Print (f)

Execution Result:

-----1.000000e+09------1.000000E+09
    • G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
    • G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
' -----% (num) g------% (NUM1) G'%{'num': 1000000000,'num1  ': ' + 'print(g)

Execution Result:

-----1e+09------100
    • %, when there is a formatting flag in the string, a percent sign (similar to the turn effect) is required
' AAA% ' Print  'AAA%s percent'('bbb')print( S1)

Execution Result:

AAA%
format Mode

[[Fill]align] [Sign] [#] [0] [Width] [,] [. Precision] [Type]

    • Fill "optional" white space filled with characters
    • Align "optional" alignment (required with width)
        • <, content left justified
        • Content right-aligned (default)
        • =, the content is right-aligned, the symbol is placed to the left of the padding character, and only valid for numeric types. Even: symbol + filler + number
        • ^, content centered
    • Sign "optional" with unsigned numbers
      • +, positive home Plus, minus plus negative;
      • -The plus sign does not change, minus is negative;
      • Spaces, plus spaces, minus signs and negative;
    • # "optional" for binary, octal, hex, if added #, 0b/0o/0x is displayed, otherwise not displayed
    • , "optional" adds a delimiter to the number, such as: 1,000,000
    • width "Optional" format the size of the placeholder
    • . Precision "optional" decimal digits reserved Precision
    • Type "optional" formatting types
      • Parameters passed into the string type
        • s, format string type data
        • Blank, no type specified, default is None, same as S
      • Parameters passed into the integer type
        • B, automatic conversion of 10 binary integers to 2 binary representation and then formatting
        • C, automatic conversion of 10 binary integers to their corresponding Unicode characters
        • d, decimal integer
        • O, the 10 binary integers are automatically converted to 8 binary representation and then formatted;
        • X, automatically converts 10 binary integers to 16 binary representation and then formats (lowercase x)
        • X, automatically converts 10 binary integers to 16 binary representation and then formats (uppercase X)
      • Parameters passed in floating-point or decimal type
        • E, converted to scientific notation (lowercase e), and then formatted;
        • E, converted to scientific notation (capital E), and then formatted;
        • F, converted to floating-point type (6 digits after the default decimal point), and then formatted;
        • F, converted to floating-point type (6 digits after the default decimal point), and then formatted;
        • G, automatically switch between E and F
        • G, automatically switch between E and F
        • %, display percent (default 6 digits after decimal)

Fill "optional" white space filled with characters

Align "optional" alignment (required with width)

      • <, content left justified
      • Content right-aligned (default)
      • =, the content is right-aligned, the symbol is placed to the left of the padding character, and only valid for numeric types. Even: symbol + filler + number
      • ^, content centered

width "Optional" format the size of the placeholder

S1 ='---{:* ^20s}----'. Format ('Welcome')Print(s1) S2='---{:* >20s}----'. Format ('Welcome')Print(S2) S3='---{:* <20s}----'. Format ('Welcome')Print(S3)

Execution Result:

---******welcome*******-------*************welcome-------welcome*************----

# "optional" for binary, octal, hex, if added #, 0b/0o/0x is displayed, otherwise not displayed

    • B, automatic conversion of 10 binary integers to 2 binary representation and then formatting
    • C, automatic conversion of 10 binary integers to their corresponding Unicode characters
    • d, decimal integer
    • O, the 10 binary integers are automatically converted to 8 binary representation and then formatted;
    • X, automatically converts 10 binary integers to 16 binary representation and then formats (lowercase x)
    • X, automatically converts 10 binary integers to 16 binary representation and then formats (uppercase X)

Three methods of representation

" numbers: {: b},{:o},{:d},{:x},{:x}, {:%},{:c} ". Format (all, 15.87623,65,"numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%} , {1:c}". Format (15,65"numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num: %},{CC:C}". Format (num=15,cc=65)Print(A1)print  (A2) Print (A3)

Execution Result:

Numbers:1111,17,15,f,f, 1587.623000%,a
Numbers:1111,17,15,f,f, 1500.000000%,a
Numbers:1111,17,15,f,f, 1500.000000%,a

, "optional" adds a delimiter to the number, such as: 1,000,000

. Precision "optional" decimal digits reserved Precision

' ---{:, d}---- '. Format (10000000'---{:. 2f}----'. Format (1.2345)  Print(n)print(N1)

Execution Result:

---10,000,000-------1.23----

Format Common formatting

TP1 ="I am {}, age {}, {}". Format ("Seven", 18,'Alex') TP2="I am {}, age {}, {}". Format (*["Seven", 18,'Alex']) TP3="I am {0}, age {1}, really {0}". Format ("Seven", 18) TP4="I am {0}, age {1}, really {0}". Format (*["Seven", 18]) TP5="I am {name}, age {age}, really {name}". Format (name="Seven", age=18) TP6="I am {name}, age {age}, really {name}". Format (**{"name":"Seven"," Age": 18}) TP7="I am {0[0]}, age {0[1]}, really {0[2]}". format ([1, 2, 3], [11, 22, 33]) TP8="I am {: s}, age {:d}, Money {: F}". Format ("Seven", 18, 88888.1) TP9="I am {: s}, age {:d}". Format (*["Seven", 18]) Tp10="I am {name:s}, age {age:d}". Format (name="Seven", age=18) Tp11="I am {name:s}, age {age:d}". Format (**{"name":"Seven"," Age": 18})Print(TP1)Print(TP2)Print(TP3)Print(TP4)Print(TP5)Print(TP6)Print(TP7)Print(TP8)Print(TP9)Print(TP10)Print(TP11)

Execution Result:

Iam seven,age of1, age 2, really 318, Money 88888.10000018

Python string formatting

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.