Python learning "The 11th article" Basic Grocery

Source: Internet
Author: User

String formatting

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.

Percent-Semicolon 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:

s = "My name is%s ' and" is%d "% (" Bourbon ") print (s) # output My name is bourbon and the is 22# name: formatted by name s =" My name I S% (name) s and age are% (age) d "%{' name ':" Bourbon ", ' Age ': 23}print (s) # output My name is bourbon and an IS 22s1 =" My name is% "P Rint (S1) # output My name is% # when formatting, the placeholder%s appears in the string: Needs to be output%S2 = "My name is%s percent"% ("Bourbon") print (S2) # output My name is Bourbon%S3 = "percent%.2f"% 99.97623print (S3) # Output per cent 99.98S4 = "I am% (PP)." 2f "% {" pp ": 123.425556,}print (S4) # Output I am 123.43
Format method:
[[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)

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: {0:b},{0: O},{0:d},{0:x},{0:x}, {0:%} ". Format () 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

Generators and iterators:

1. Generator:

Instead of saving the results in a series, the generator saves the state of the generator and returns a value each time it is iterated.

Li = [11,22,33,44]result = filter (lambda x:x>22, Li) print (Result) # An object with the ability to generate the specified condition data # output <filter object at 0x000000 00010fd588>

Generator, using functions created by the

# normal function # def func (): #     return 123## ret = func () def func ():    print (' start ')    yield 1    yield 2    yield 3func ( # function does not perform RET = func () print (ret) # in the normal function there is yield, then this function is the generator for the I in RET:    print (i) # output <generator object func at 0x 00000000006b6c50>start123

2. Iterators:

Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files

Characteristics:

    1. The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
    2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
    3. You can't go back halfway through the interview.
    4. Facilitates recycling of large data sets, saving memory

In the code above: Func is a function called a generator, and when you execute this function func () you get an iterator.

ret = func () r1 = ret.__next__ () # Enter function to find yield, get data print after yield (R1) # Output START1R2 = ret.__next__ () # Enter function to find yield, get yield back Data print (R2) # Output 2R3 = ret.__next__ () # Enter function to find yield, get data after yield print (R3) # output 3

3. Example:

Def myrange (ARG):    start = 0 while    True:        If Start > arg:            return        yield start        start + = 1ret = Myra Nge () # ret.__next__ () # iterating through for-item in RET:    print (item)

  

Python learning "The 11th article" Basic Grocery

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.