Python3 string Formatting

Source: Internet
Author: User

There are two ways to format a string in Python: The percent-percent placeholder (%) and format mode. The percent of the semicolon is relatively old, and format is a more advanced way to replace the old way, the two coexist. The placeholder method is widely used in python2.x, and as the python3.x is used more widely, the format method is more extensive.

First, percent semicolon placeholder (%) mode

%[(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

Common formatting:

TPL = "I am%s"% "Alex" TPL = "I am%s age%d"% ("Alex", +) TPL = "I am% (name) s age% (age) d"% {"name": "Alex", "Age": TPL = "percent%.2f"% 99.97623 TPL = "I am% (PP)." 2f "% {" pp ": 123.425556,} TPL =" I am%.2f percent "% {" pp ": 123.425556 , }

Second, 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
      • incoming string type" Parameters
        • s, format string type data
        • blank, unspecified type, default is None, with S
      • incoming "integer type" Parameters
        • b, Automatically converts a 10-based integer to a 2-binary representation and then formats the
        • C, automatically converts 10 binary integers to their corresponding Unicode characters
        • d, decimal integer
        • o, Automatically converts a 10-based integer to a 8-binary representation and then formats it;
        • 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)

Location mapping

Example (python3.0+):
Print ("{}:{}". Format (' 192.168.0.100 ', 8888)) #192.168.0.100:8888
Keyword mapping

Example (python3.0+):
Print ("{server}{1}:{0}". Format (8888, ' 192.168.1.100 ', server= ' Web server Info: ') #Web server info:192.168.1.100:8888
Element access

Example (python3.0+):
Print ("{0[0]}.{ 0[1]} ". Format ((' Baidu ', ' com ')) #baidu. com

Fill-in alignment
    1. ^, <, > center, Align Left, align right

Example 1 (python3.0+):
Print ("{0}*{1}={2:0>2}". Format (3,2,2*3)) #3 *2=06 print ("{:* ^30}". Format (' centered ')) #***********centered***** ******

Example 2 (python3.0+): 99 multiplication Table
For I in Range (1,10):    a = 1    while a <= i:        print ("{0}*{1}={2:0>2}". Format (a,i,a*i), end= "\ T")        a +=1    print () "" "     1*1=01 1*2=02  2*2=04 1*3=03  2*3=06  3*3=09 1*4=04  2*4=08  3*4=12  4*4 =16 1*5=05  2*5=10  3*5=15  4*5=20  5*5=25 1*6=06  2*6=12  3*6=18  4*6=24  5*6=  6*6=36 1*7=07  2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49 1*8=08  2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64 1*9=09  2*9=18  3*9=27  9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81 "" "

Precision setting

Example (python3.0+):
Print ("{:. 3f}". Format (2.1415)) #2.142print ("{:. 10f}". Format (3.1415)) #3.1415000000

  common formatting:

TPL = "I am {}, age {}, {}". Format ("Seven", ' Alex ') TPL = "I am {}, age {}, {}". Format (*["Seven", "Alex"]) TPL = "I am {0}, age {1}, really {0}". Format ("seven", +) TPL = "I am {0}, age {1}, really {0}". Format (*["seven", +]) TPL = "I am {name}, age {age}, really {name}". Format (name= "Seven", age=18) TPL = "I am {name}, age {age}, really {name}". Format  (**{"name": "Seven", "age": +) TPL = "I am {0[0]}, age {0[1]}, really {0[2]}". Format ([1, 2, 3], [One, All,]) TPL = "I  AM {: s}, age {:d}, Money {: F} '. Format ("Seven", 88888.1) TPL = "I am {: s}, age {:d}". Format (*["seven", +]) TPL = "I AM {name:s}, age {age:d} '. Format (name= "Seven", age=18) TPL = "I am {name:s}, age {age:d}". Format (**{"name": "Seven", "AG E ": ()) TPL =" Numbers: {: b},{:o},{:d},{:x},{:x}, {:%} ". Format (2, F, F, F, 15.87623,) TPL =" Numbers: {: B},{:o} , {:d},{:x},{:x}, {:%} ". Format (2, +, +, 15.87623, +), TPL =" numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%} ". forma T () TPL = "Numbers: {nUm:b},{num:o},{num:d},{num:x},{num:x}, {num:%} ". Format (NUM=15) 

More formatting operations: https://docs.python.org/3/library/string.html

Resources:

Https://www.cnblogs.com/lvcm/p/8859225.html

Http://www.cnblogs.com/wupeiqi/articles/5484747.html

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