"Python-day5 (string formatting, generators, iterators)"

Source: Internet
Author: User

First, string formatting

Mode 1: Placeholder--%

%[(name)][flags][width]. [Precision]typecode
(name) optional to select the specified key flags, the optional values are:+right-justified, positive plus, negative before plus minus;-left-aligned, positive number before unsigned, negative before plus minus, space right-aligned, positive with a space, negative before plus minus, 0 right-aligned, positive sign before negative, plus minus before minus; fill blank width with 0 Optional, occupied width .precision optional, number of digits retained after the decimal point TypeCode required S, gets the return value of the __str__ method of the incoming object, and formats it to the specified position R to get the __r of the incoming object Epr__ The return value of the 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, converts an integer, floating-point number to a decimal representation, and formats To the specified position E, converts an integer, floating-point number into scientific notation, and formats it to a specified position (lowercase e) E, converts an integer, floating-point number to scientific notation, and formats it to a specified position (capital E) F, converts an integer, floating-point number to a floating-point representation, and formats To the specified position (the default is 6 digits after the decimal point) F, ditto G, auto-adjust the integer, floating-point number conversion to float or scientific notation (more than 6 digits in scientific notation), and format it to the specified position (if the scientific count is E;) G, automatically adjusts the integer, Floating-point numbers are converted to floating-point or scientific notation (more than 6 digits in scientific notation) and formatted to the specified position (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

Example

TPL ="I am%s"%"Alex"Print(TPL)-I am alextpl="I am%s age%d"% ("Alex", 18)Print(TPL)-I am Alex age 18TPL="I am% (name) s age percent (age) D"% {"name":"Alex"," Age": 18}Print(TPL)-I am Alex age 18TPL="percent%.2f"% 99.97623Print(TPL)-Percent 99.98TPL="I am% (PP). 2f"% {"pp": 123.425556, }Print(TPL)-I am 123.43

Mode 2:format (more features)

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

    Fill "optional" padding character align "optional" alignment (need to use with width) <, content left-justified, content right-aligned (default) =, The content is right-aligned, placing the symbol on the left side of the fill character, and only valid for numeric types.    Even if: symbol + filler + Number ^, the content center sign "optional" has unsigned number +, plus home plus, minus negative;-, plus constant, minus negative; spaces, plus spaces, minus and negative; # "optional" for binary, octal, hexadecimal, if you add #, it will display 0b/0o/0x, otherwise not display, "optional" to add separators for numbers, such as: 1,000,000 width "optional            "Format bits occupy width .precision" optional "decimal reserved precision type" Optional "format type passed in" string type "parameter s, format string type data            Blank, unspecified type, default is None, with s passed parameter B of "integer type", the 10 binary integer is automatically converted to 2 binary representation and then formatted C, the 10 binary integers are automatically converted to their corresponding Unicode characters d, decimal integer o, automatically converts 10 binary integers to 8 notation and then formats; x, automatically converts 10 binary integers to 16 binary representation and then formats (lowercase x) x, automatically converts 10 binary integers to 16            The system representation is then formatted (uppercase X) into the "float or decimal type" parameter E, converted to scientific notation (lowercase e), then formatted, E, converted to scientific notation (capital E), and then formatted; F, converted to floating point (6 bits after the default decimal point) is represented, then formatted, F, converted to floating point (6 bits left after the default decimal point), and then formatted; G, automatically switches G in E and F, self-Toggle% in E and F, display percent (default is 6 digits after decimal) 

Example

#leave two decimal places (rounded) and convert to percentagesA ="num is {:. 2%}". Format (0.123456)Print(a)-Num is12.35%#placeholder is empty, formatted sequentiallyTPL ="I am {}, age {}, {}". Format ("Hexu", 18,'God')Print(TPL)-I am hexu, age 18, God#can be in the form of a list, before the list to add *TPL ="I am {}, age {}, {}". Format (*["Hexu", 18,'God'])Print(TPL)-I am hexu, age 18, God#formatted according to index (subscript)TPL ="I am {0}, age {1}, really {0}". Format ("Hexu", 18)Print(TPL)-I am hexu, age 18, really hexu#formatted according to index (subscript), also available in listTPL ="I am {0}, age {1}, really {0}". Format (*["Hexu", 18])Print(TPL)-I am hexu, age 18, really hexu#according to the name of the specific parameterTPL ="I am {name}, age {age}, really {name}". Format (name="Hexu", age=18)Print(TPL)-I am hexu, age 18, really hexu#use a dictionary to pass a value, before the dictionary to add * *TPL ="I am {name}, age {age}, really {name}". Format (**{"name":"Hexu"," Age": 18})Print(TPL)-I am hexu, age 18, really hexu#Index in Index#{0} is [1, 2, 3],{0[0]} is 1TPL ="I am {0[0]}, age {0[1]}, really {0[2]}". format ([1, 2, 3], [11, 22, 33])Print(TPL)-I am 1, age 2, really 3#: s string#:d Decimal (integer)#: F floating pointTPL ="I am {: s}, age {:d}, Money {: F}". Format ("Hexu", 18, 99999.99)Print(TPL)-I am hexu, age, Money 99999.990000#List FormTPL ="I am {: s}, age {:d}". Format (*["Hexu", 18])Print(TPL)-I am hexu, age 18#TPL ="I am {name:s}, age {age:d}". Format (name="Xuelu", age=16)Print(TPL)-I am xuelu, age 16#Dictionary FormTPL ="I am {name:s}, age {age:d}". Format (**{"name":"Hexu"," Age": 18})Print(TPL)-I am hexu, age 18#format the following parameters in the corresponding format#: 0 octal Binary#: x hexadecimalTPL ="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2)Print(TPL)-Numbers:1111,17,15,f,f, 1587.623%#by index, index 0 is theTPL ="numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%}". Format (88)Print(TPL)-Numbers:1011000,130,88,58,58, 8,800%#depending on the specific variable nameTPL ="numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num:%}". Format (num=99)Print(TPL)-Numbers:1100011,143,99,63,63, 9,900%

Second, iterators and generators

1. iterators

Iterators are a way to access the elements of a collection. An iterator object is accessed from the first element of the collection, knowing that 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.

To be blunt is to perform a specific action.

Iterator Features:

(1) For native support random access data structures (such as tuple, list), the iterator and the classic for loop index access compared with no advantage, but lost the index value (can use the built-in function enumerate () to retrieve the index value). But for data structures that cannot be accessed randomly (such as set), iterators are the only way to access elements.

(2) All elements in the entire iteration are not required to be prepared beforehand. 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 particularly useful for traversing large or infinite collections, such as several G files, or Fibonacci sequences, and so on.

(3) provides a unified access to the collection of interfaces, as long as the __iter__ () method object is defined, you can use an iterator access.

Iterator method:

(1) Next method: Returns the next element of the iterator
(2) __iter__ method: Returns the Iterator object itself

2. Generator

When a function call returns an iterator, the function is called the Generator (generator). If the function contains the yield syntax, the function becomes the generator.

Generators are created with functions that are creative. The essence of the generator is yield.

(1) Simple Generator example

def func ():     Print ('start')     yield 1    yield 2    yield 3func ()  #  Executes the Func function, But the output has no content

(2) Generator + iterator

#yield+next mode, equivalent to a for loopdeffunc ():Print(1111)    yield1Print(2222)    yield2Print(3333)    yield3ret=func ()#to find yield in a function sequentiallyR1 = Ret.__next__()#enter function to find Yield1, get the data after Yield1Print(R1) R2= Ret.__next__()#enter function to find Yield2, get the data after Yield2Print(R2) R3= Ret.__next__()#enter function to find yield3, get the data after yield3Print(R3)
View Code

(3) using the generator to customize the range

defmyrange (ARG): Start=0 whileTrue:ifStart >ARG:return        yieldStart Start+ = 1ret= myrange (3) R= Ret.__next__()Print(r) R= Ret.__next__()Print(r) R= Ret.__next__()Print(r) R= Ret.__next__()Print(r)
View Code

Third, recursion

The loop executes the same program until a conditional end call is met.

def func (N):     + = 1  #  (1) func is 1,n is 2  (3) func is 2,n is 3 (5) func is 3,n is 4    if n >=4        : return ' End '  # (6) greater than or equal to 4 o'clock, return ' End '    return func (n)  #  (2) Here is 2 (4) Here is 3  r = func (1)print( R)  #  (7) Final return ' End '

Using recursion to achieve factorial:1*2*3*4*5*6*7

def func (N):     if or n==1:         return 1    return n*func (n-1)  #  7*func (6 then Func (6) is 6*func (5) and then always recursively to func (1) returns 1 is 7*6*5*4*3*2*1r = func (7)print(r)

"Python-day5 (string formatting, generators, iterators)"

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.