Python Learning: 12. String formatting

Source: Internet
Author: User

String formatting

We've been explaining Python for so long and haven't explained the format of the Python string, so let's look at the power of Python string formatting today.

Two ways to format a string

Percent of the way and format, the percent is older, and format mode is more advanced, try to replace the old way, the two coexist, and then we will explain the two ways.

1. Percent-Semicolon mode
' Alexsel ' Print ('name:%s'%name)

This is a simple way to use the percent output variable, and there are many optional parameters inside the percent sign.

%[(name)][flags][width]. [Precision]typecode (name) optional, used to select the specified key flags is optional, the values to choose from are as follows:+right-justified, positive plus, negative before plus minus;-left-aligned, positive number before unsigned, negative before plus minus, space right-aligned, positive with a blank, negative before plus minus, 0 right-aligned, positive sign before negative, minus with 0 padding
Width optional, occupies a wide. Precision optional, the number of digits reserved after the decimal point TypeCode required, the available parameters are as follows: s, gets the __str__ method of the incoming object. Returns the value and formats it to the specified position R, gets the return value of the passed-in object's __repr__ method, and formats it to the specified position C, integer: Converts the number to its Unicode corresponding value, 10 of the binary range is 0<= i <= 1114111 (py27 only supports 0-255) Character: Adds a character to the specified position O, converts an integer to an octal representation, formats it to a specified position x, converts an integer to a hexadecimal representation, and formats it to a specified position d, converting an integer, floating-point number to Decimal representation, and formatting it to the specified position e, converting an integer, floating-point number to scientific notation, and formatting it to a specified position (lowercase e) e, converting an integer, floating-point number to scientific notation, and formatting it to the specified position (capital E) F, converting integers, floating-point numbers to floating-point number representations, and formatting them to a specified location (by default, 6 digits after the decimal point) F, ditto G, auto-adjust to convert integers, floating-point numbers to float or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (If the scientific count is E;) G, auto-adjust converts integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and formats them to a specified location (if the scientific count is E;)*%, when there is a format flag in the string, you need to use a percentrepresents a percent semicolon#two% required to write placeholders in a string

Next, we'll go directly to the example

>>> s ="I am%s age%d"%("Baba", 16)>>>Print(s) I am Baba age16>>> s ="I am% (N1) s age% (n2) d"%{"N1":"Alexsel","N2": 29}>>>Print(s) I am Alexsel age29#set a name for a placeholder>>> s ="I am% (N1) s age% (N1) s"% {"N1":"Alexsel"}>>>Print(s) I am Alexsel age Alexsel>>> s ="I am% (N1) +10s age% (N1) s"% {"N1":"Alexsel"}#Add 10 spaces>>>Print(s) I am Alexsel age Alexsel>>> s ="I am% (N1) 010s age% (N1) s"% {"N1":"Alexsel"}#Align Right>>>Print(s) I am Alexsel age Alexsel>>> s ="I am% (N1) +010d age% (N1) d"% {"N1": 19}#Align Right with 0>>>Print(s) I am+000000019 Age 19>>> S ="I am%.2f age"% (1.2)#two-bit decimal point f default 6-bit>>>Print(s) I am1.20 Age>>> s ="I am%c"% (250)#symbols corresponding to Unicode codes>>>Print(s) I amú

Common formatting:

>>> TPL ="I am%s"%"Alex">>>Print(TPL) I am Alex>>> TPL ="I am%s age%d"% ("Alexsel", 18)>>>Print(TPL) I am alexsel age18>>> TPL ="I am% (name) s age percent (age) D"% {"name":"Alexsel"," Age>>>Print(TPL) I am alexsel age18>>> TPL ="percent%.2f"% 99.97623>>>Print(TPL) percent99.98>>> TPL ="I am% (PP). 2f"% {"pp": 123.425556, }>>>Print(TPL) I am123.43>>> TPL ="I am%.2f percent"% (123.425556,)>>>Print(TPL) I am123.43%

When the string formatting is used in a dictionary, the dictionary form of the string formatting method, there is one of the biggest advantage is that the dictionary this thing can and JSON files to each other, so, when the configuration file using string settings, it seems very convenient.

2.format Formatting

Format formatting is more powerful than the percent formatting feature, and after a simple example, let's take a look at its optional parameters.

' Name:{:s} '. Format ('alexsel')print(s)

Format notation and optional parameters

[[Fill]align] [Sign] [#] [0][width][,][.precision][type] Fill "optional" padding character align "optional" alignment (need to use with width) <, content left justified>, the content is 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: Symbols+ Filler +Digital^, Content center sign "optional" with unsigned numbers+, plus home plus, minus negative;-, the plus sign is constant, minus is negative, a space, a positive space, a minus sign plus a negative; # "optional" for binary, octal, hexadecimal, if you add #, it will show 0b/0o/0x, otherwise not displayed, "optional" to add separators for numbers, such as:1, the, theWidth "Optional" format the number of digits. Precision "optional" decimal digits reserved Precision type "Optional" format types***********#在以下格式化前需加: Passed parameter S of "string type", formatted string type data blank, unspecified type, default is None, with S pass                Into the "integer type" parameter B, the 10-binary integer is automatically converted to a 2-binary representation and then formatted C, the 10-binary integer is automatically converted to its corresponding Unicode character D, Decimal integer o, the 10-binary integer is automatically converted to 8 binary representation and then formatted; x, the 10-decimal integer is automatically converted to a 16-binary representation and then formatted (lowercase x ) X, converts a 10-decimal integer into a 16-binary representation and then formats (Caps X) The parameter e passed in "floating-point or decimal type", converted to scientific notation (lowercase e), and        E, converted to scientific notation (capital E), and then formatted; F, converted to floating point (6 digits after the default decimal point), and then formatted; F, converted to floating point (6 digits after the default decimal point) is represented, then formatted; G, automatically in E and F Toggle G, automatically toggle% in E and F, display percent (default 6 digits)

Common formatting:

>>> TPL ="I am {}, age {}, {}". Format ("Seven", 18,'Alex')>>>Print(TPL) I am seven, age18, Alex>>> TPL ="I am {}, age {}, {}". Format (*["Seven", 18,'Alex'])>>>Print(TPL) I am seven, age18, Alex>>> TPL ="I am {0}, age {1}, really {0}". Format ("Seven", 18)>>>Print(TPL) I am seven, age18, really seven>>> TPL ="I am {0}, age {1}, really {0}". Format (*["Seven", 18])>>>Print(TPL) I am seven, age18, really seven>>> TPL ="I am {name}, age {age}, really {name}". Format (name="Seven", age=18)>>>Print(TPL) I am seven, age18, really seven>>> TPL ="I am {name}, age {age}, really {name}". Format (**{"name":"Seven","AGE":)>>>Print(TPL) I am seven, age18, really seven>>> TPL ="I am {0[0]}, age {0[1]}, really {0[2]}". format ([1, 2, 3], [11, 22, 33])>>>Print(TPL) I am1, age 2, really 3>>> TPL ="I am {: s}, age {:d}, Money {: F}". Format ("Seven", 18, 88888.1)>>>Print(TPL) I am seven, age, Money 88888.100000>>> TPL ="I am {: s}, age {:d}". Format (*["Seven", 18])>>>Print(TPL) I am seven, age18>>> TPL ="I am {name:s}, age {age:d}". Format (name="Seven", age=18)>>>Print(TPL) I am seven, age18>>> TPL ="I am {name:s}, age {age:d}". Format (**{"name":"Seven"," Age": 18})>>>Print(TPL) I am seven, age18>>> TPL ="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2)>>>Print(TPL) numbers:1111,17,15,f,f, 1587.623000%>>> TPL ="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2)>>>Print(TPL) numbers:1111,17,15,f,f, 1587.623000%>>> TPL ="numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%}". Format (15)>>>Print(TPL) numbers:1111,17,15,f,f, 1500.000000%>>> TPL ="numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num:%}". Format (num=15)>>>Print(TPL) numbers:1111,17,15,f,f, 1500%

Both formats are convenient to use, but we can choose the more powerful format to learn, format string formatting the main use of parameters need our focus on memory.

Python Learning: 12. 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.