Python Learning-string formatting

Source: Internet
Author: User

There are two ways to format a Python string: a percent-semicolon, 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.

1, percent of the way

When formatting a string, Python uses a string as a template. There are formatting characters in the template that reserve locations for real values and describe the format in which real values should be rendered. Python uses a tuple to pass multiple values to the template, each of which corresponds to a format character.

For example, the following:

Print ("I ' m%s.") I ' m%d year old "% (' Vamei ', 99))

In the example above, "I ' m%s." I ' m%d year old "for our template. %s is the first format character, which represents a string. %d is the second format character, which represents an integer. (' Vamei ', 99) Two elements ' Vamei ' and 99 are substituted for the true values of%s and%d.

Between the template and the tuple, there is a% number separated, which represents the format operation.


We can also use dictionaries to pass real values. As follows:

Print ("I ' m% (name) s. I ' m% (age) d year old "% {' name ': ' Vamei ', ' Age ': 99})

As you can see, we have named two of the format characters. The name is used () enclosed. A key for each named corresponding dictionary.


The format can be further controlled in the following ways:

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

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

2. Format mode


It has a rich "format qualifier" (syntax is {} with: number)


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

· Fill "optional" white space filled with characters

· Align "optional" alignment (required with width)

< content left Justified

> Right align Content (default)

= content is right-aligned, placing the symbol to the left of the fill 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 is constant, minus is negative;

Empty line space, minus sign plus negative;

# "Optional" for binary, octal, hex, if Add #, will display 0b/0o/0x, otherwise not display

width The width of the "optional" format bit

• "optional" adds separators for numbers, such as: 1,000,000

·. Precision "optional" decimal digits reserved Precision

type "optional" format type

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)


Common formatting:

sl =  "i am {}, age {}, {}". Format ("Seven", 18,  ' Alex ') sl =   "i am {}, age {}, {}". Format (*["Seven", 18,  ' Alex ']) sl =  "I &NBSP;AM&NBSP;{0},&NBSP;AGE&NBSP;{1},&NBSP;REALLY&NBSP;{0} ". Format (" Seven ",  18) sl = " I am &NBSP;{0},&NBSP;AGE&NBSP;{1},&NBSP;REALLY&NBSP;{0} ". Format (*[" Seven ",  18]) sl = " i am  {name}, age {age}, really {name} ". Format (name=" Seven ",  age=18) sl = " i  Am {name}, age {age}, really {name} ". Format (**{" name ": " seven ", " age ": &NBSP;18}) sl =  "i am {0[0]}, age {0[1]}, really {0[2]}". Format ([1, &NBSP;2,&NBSP;3],&NBSP;[11,&NBSP;22,&NBSP;33]) sl =  "i am {:s}, age {:d},  MONEY&NBSP;{:F} ". Format (" Seven ",  18, 88888.1) sl = " i am {:s}, age {:d} ". Format (*[" Seven ", &nbsp) sl =  "I am {name:s}, age {age:d}". Format (name= "Seven",  age=18) sl  =  "I am {name:s}, age {age:d}". Format (**{"name":  "seven",  "Age":  18}) sl =  "numbers: {:b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15,  15,&NBSP;15.87623,&NBSP;2) sl =  "numbers: {:b},{:o},{:d},{:x},{:x}, {:%}". Format (15,  15,&NBSP;15,&NBSP;15,&NBSP;15,&NBSP;15.87623,&NBSP;2) sl =  "numbers: {0:b},{0:o},{0:d},{0:x},{0: x}, {0:%} ". Format (sl = " numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num:%} " . Format (NUM=15)


This article is from the "LE" blog, please be sure to keep this source http://lz001.blog.51cto.com/8294567/1825737

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