Python Learning Journey-Basics (v) string formatting, recursion, generators & iterators, modules

Source: Internet
Author: User

This article highlights:
String formatting
Recursive
Generators and iterators
Module

First, string formatting
Two ways to format a string: placeholder%, Format function
1, placeholder%

%[(name)][flags][width]. [Precision]typecode
 -(name) is optional to select the specified key-flags selectable values are:-+ right-aligned, positive plus, negative before plus minus;--left alignment; positive front unsigned, Negative number before plus minus;-space right to align, positive number before adding a space, negative before plus minus;-0 right-aligned, positive front unsigned, negative before minus; fill in blanks with 0-width optional, occupied width-. Precision optional, digits retained after decimal point-typecode required-s, get incoming to The return value of the __str__ method, and formats it to the specified position-R, gets the return value of the __repr__ method of the passed-in object, and formats it to the specified position-C, Integer: Converts the number to its Unicode corresponding value, the 10 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 and formats it to the 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 it to a specified position-E, converts an integer, floating-point number to scientific notation, and formats it to a specified position (lowercase e)-e, converting integers, floating-point numbers into scientific notation, and formats it to the specified position (capital E)-F, converts an integer, floating-point number to a floating-point representation, and formats it to a specified position (the default is 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 formats it to the specified location (if the scientific count is E;)-G, auto-adjust the conversion of integers, floating-point numbers into floating-point or scientific notation (more than 6 digits in scientific notation), and format it to a specified position (if the scientific count is e;)-%, when there is a format flag in the string, you need to use the Percent percent represents a semicolon  

Note: There is no way to automatically convert an integer to a binary representation in Python with a percent-semicolon format

Practice:

TPL = "I am%s"% "Alex" Print (TPL) TPL = "I am%s age%d"% ("Alex", page) print (TPL) TPL = "I am% (name)" s age% (age) d "% {" NA Me ":" Alex "," Age ": 18}print (TPL) TPL =" percent%.2f "% 99.97623print (TPL) TPL =" I am% (PP). "2f"% {"pp": 123.425556,}prin T (TPL) TPL = "I am%.2f%"% {"pp": 123.425556,}print (TPL)

2, Format (*args, **kwargs) function mode

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

<>Right-aligned content (default)-=, content right-aligned, places the symbol on the left side of the fill character, and is only valid for numeric types. Even if: symbol + padding + number-^, Content center-sign "optional" has unsigned number-+, positive home Plus, minus plus negative;----, plus constant, minus and negative;-# "optional" for binary, octal, hexadecimal, if added #, it will show 0b/0o/ 0x, otherwise do not display-, "optional" to add separators for numbers, such as: 1,000,000-width "optional" format bit to occupy the width-. Precision "optional" decimal digit reserved precision-type "optional" format type-the parameter passed in "string type"-S, format string Type data-blank, unspecified type, default is None, with S-pass argument of "integer type"-B, the 10-decimal integer is automatically converted to a 2-binary representation and then formatted-C, the 10-decimal integer is automatically converted to its corresponding Unicode character-D, the integer-O, Converts a 10-decimal integer into a 8-binary representation and then formats it;-X, automatically converts the 10 binary integers to a 16 binary representation and then formats (lowercase x)-X, converts the 10-decimal integer into a 16-binary representation and then formats (uppercase X)-the parameter that passes in the floating-point or decimal type-E, Converted to scientific notation (lowercase e) is represented, then formatted;-E, converted to scientific notation (uppercase E) is represented, then formatted;-F, converted to floating point (6 bits after the default decimal point) is represented, then formatted;-F, converted to floating point (the default decimal point retains 6 bits), and then formatted;-G, Automatically switch between E and F-G, automatically toggle between E and F-%, display percent (default 6 digits)

Practice:

s = "name is {}, age {}.". Format ("Pesen") print (s) s = "name is {}, age {}.". Format (*["Pesen", +]) print (s) s = "name is {0}, age {1}, retry name is {0}". Format ("Pesen",) print (s) s = "name is {0}, a GE {1}, retry name is {0} ". Format (*[" Pesen ", +]) print (s) s =" name is {name}, age {age}, and retry name is {name} ". Format (Name = "Pesen", age=18) print (s) s = "name is {name}, age {age}, retry name ' is {name} '. Format (**{" name ":" Pesen "," Age ":) print (s) s = "name is {0[0]}, age {0[1]}, retry name is {1[0]}". Format (["Pesen", +], ["Xie", "job"]) print (s) s = "name is {n Ame:s}, age {Age:d},money is {money:.2f} '. Format (**{"name": "Pesen", "Age": "$", "$") print (s) numb = "binary: {: b}; Octal: {: o}; Decimal: {:d}; "" Hex: {: x}; Hex: {: X}, Percent: {:. 3%} ". Format (*[15, 0.0998, 122344]) print (numb) numb =" binary: {: #b}; Octal: {: #o}; Decimal: {: #d}; "" Hex: {: #x}; Hexadecimal: {: #X}, Percent: {:. 3%} ". Format (*[15, 0.0998, 122344]) print (numb) 

Second, recursion
The loop executes the same program, knowing that a condition is met to end the call.

def func (numb): Numb + = 1print (numb) If numb >= 10:return "END" return func (numb) ret = func (0) print (ret)


Study questions: Recursive implementation 1*2*3*4*5*6*7

def func (Numb, Times): times + = 1numb = Numb * timesif times > 7:return "END" else:print (numb) return func (Numb, Times) ret = func (1, 0) print (ret) print (1 * 2 * 3 * 4 * 5 * 6 * 7)

Iii. Generators and iterators
Generator: A function with yield is called a generator (generator) in Python. Example:
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.

Advantages of using iterators:
For primitive data structures that support random access (such as tuple, list), there is no advantage over the index access of the iterator and the classic for loop, but the index value is lost (you 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.

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 particularly useful for traversing large or infinite collections, such as several G files, or Fibonacci sequences, and so on.

The greater credit for iterators is the provision of an interface for a unified access collection, which can be accessed using iterators as long as the __iter__ () method object is defined.

There are two basic methods for iterators:
Next method: Returns the next element of the iterator
__iter__ method: Returns the Iterator object itself

def func ():p rint (111) yield 11print (222) yield 22print (333) Yield 33ret = func () print (ret) # An object that can generate a function execution result <generator The object func at 0x1013857d8># is used by the iterator itself, so the amount of memory space used is always a constant for the I in Ret:print (1) When the value is taken.

Builder, iterator Example: Analog xrange () def myrange (args): start = 0while true:if Start > Args:returnyield StartStart + = 1ret = myrange (3) PR int (ret) # RET is a generator for I in Ret:print (i)

The effect of yield is to turn a function into a generator, call myrange (3) to not execute the myrange function, but return a Iterable object! When the For loop executes, each loop executes the code inside the myrange function, and when it executes to yield start, the FAB function returns an iteration value, and the next iteration, the code proceeds from the next statement of yield start, and the local variable of the function appears and last interrupted execution is exactly the same, and the function continues to execute until the yield is encountered again. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.

Python Learning Journey-Basics (v) string formatting, recursion, generators & iterators, modules

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.