Python path: Day04---python basics 4

Source: Internet
Author: User

The content of this section

1. String formatting

2. Iterators and generators

3. Decorative Device

4.Json & Pickle Data serialization

5. Software Catalog Structure specification

One, string formatting percent-sign

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

Common formatting:

TPL = "I am%s"% "Alex" TPL = "I am%s age%d"% ("Alex", +) TPL = "I am% (name) s age% (age) d"% {"name": "Alex", "Age": TPL = "percent%.2f"% 99.97623 TPL = "I am% (PP)." 2f "% {" pp ": 123.425556,} TPL =" I am%.2f percent "% {" pp ": 123.425556 , }
Format mode
TPL ="I am {}, age {}, {}". Format ("Seven", 18,'Alex') TPL="I am {}, age {}, {}". Format (*["Seven", 18,'Alex']) TPL="I am {0}, age {1}, really {0}". Format ("Seven", 18) TPL="I am {0}, age {1}, really {0}". Format (*["Seven", 18]) 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": 18}) TPL="I am {0[0]}, age {0[1]}, really {0[2]}". format ([1, 2, 3], [11, 22, 33]) TPL="I am {: s}, age {:d}, Money {: F}". Format ("Seven", 18, 88888.1) TPL="I am {: s}, age {:d}". Format (*["Seven", 18]) TPL="I am {name:s}, age {age:d}". Format (name="Seven", age=18) TPL="I am {name:s}, age {age:d}". Format (**{"name":"Seven"," Age": 18}) TPL="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2) TPL="numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (15, 15, 15, 15, 15, 15.87623, 2) TPL="numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%}". Format (15) TPL="numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num:%}". Format (NUM=15)
Common formatting Operations

More formatting operations: https://docs.python.org/3/library/string.html

Second, iterator and generator iterators

We already know that for there are several types of data that can be directly acting on a loop:

A class is a collection of data types, such as,,, list tuple , and dict set str so on;

One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

You can use to isinstance() determine whether an object is an Iterable object:

>> from Collections Import iterable>>> isinstance ([], iterable) true>>> isinstance ({}, Iterable ) true>>> isinstance (' abc ', iterable) true>>> isinstance ((x for X in range), iterable) true>> > isinstance (iterable) False

  The generator can not only be used for for loops, but it can also be next() called by the function and return the next value until the last throw StopIteration error indicates that the next value cannot continue to be returned.

* An object that can be called by next() a function and continually returns the next value is Iterator called an iterator:.

You can use to isinstance() determine whether an object is an Iterator object:

>>> from Collections Import iterator>>> isinstance ((x to X in range), Iterator) true>>> are Instance ([], Iterator) false>>> isinstance ({}, Iterator) false>>> isinstance (' abc ', Iterator) False

Generators are Iterator objects, but,, list dict str Though Iterable they are, they are not Iterator .

Turn list , dict and str wait for the Iterable Iterator function to be used iter() :

>>> Isinstance (ITER ([]), Iterator) true>>> isinstance (ITER (' abc '), Iterator) True
Generator

When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator;

def func ():    yield 1    yield 2    yield 3    yield 4

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

>>> temp = func () >>> temp.__next__ () 1>>> temp.__next__ () 2>>> temp.__next__ () 3 >>> temp.__next__ () 4>>> temp.__next__ () Traceback (most recent call last):  File "<stdin>", Line 1, in <module>stopiteration
Instance

Using the generator to customize the range

def nrange (num):    temp = 1 while    True:        temp = temp + 1        if temp >= num:            return        else:            yield t Emp
Summary

Any object that can be used for for the loop is a Iterable type;

All objects that can be used for next() functions are Iterator types, which represent a sequence of lazy computations;

Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .

The Python for loop is essentially implemented by calling next() functions, such as:

For x in [1, 2, 3, 4, 5]:    Pass

is actually exactly equivalent to:

# Get Iterator Object first: it = iter ([1, 2, 3, 4, 5]) # loop: While True:    try:        # Get Next value:        x = Next (it)    except Stopite Ration:        # exit Loop break when you encounter Stopiteration        
Three, the decoration device
#! /usr/env python#-*-coding:utf-8-*-#Version:P ython3.4# define function, for call, function inside does not execute # function name >> surrogate refers to the body def outer (func):    def Inner (a):        print ("log")        r = Func (a)        print ("befor")        return R    return inner@outer  # @ + function name  Functions: 1, automatic execution of the outer function, and the function name F1 below as a parameter passed Def F1 (ARG):             #     2, the return value of the outer function, re-assigned to F1    print (ARG)    return "chop you "@outerdef F2 ():    print (" F2 ") @outerdef F100 ():    print (" F100 ") ret = F1 (" Xiaoming ") print (ret)
#! /usr/env python#-*-coding:utf-8-*-#version:python3.4user,passwd='xiaoming','123'defAuth (auth_type):defOuter_wrapper (func):defWrapper (*args,**Kwargs): Username= Input ("Username:"). Strip () password= Input ("PASSOWRD:"). Strip ()ifAuth_type = ="Local":                ifuser = = Username andpasswd = =Password:Print("\033[32;1muser has passwd auth\033[0m") Res= Func (*args,**Kwargs)Print("Chopper Brother")                    returnResElse: Exit ("\033[31;1m password is incorrect \033[0m")            elifAuth_type = ="LDAP":                Print("Knitting ldap!")        returnwrapperreturnOuter_wrapperdefindex ():Pass@auth (Auth_type="Local")defHome ():Print("wclecome to home page")    return "Kandaoke"@auth (Auth_type="LDAP")defBBS ():Print("wclecome to BBS page") Home () BBS ()
Adorner with ParametersIv. Json & Pickle Data serialization

Reference http://www.cnblogs.com/alex3714/articles/5161349.html

Five, the Software Catalog specification directory organization way

Assuming that your project is named Foo, I would recommend the most convenient and quick directory structure that would suffice:

foo/|--bin/|   | --foo| | --foo/|   | --tests/|   |   | --__init__.py|   |   | --test_main.py|   | |   | --__init__.py|   | --main.py| | --docs/|   | --conf.py|   | --abc.rst| | --setup.py|--requirements.txt|--README

Briefly explain:

    1. bin/: Store some executable files of the project, of course you can name and script/ so on.
    2. foo/: stores all source code for the project. (1) All modules and packages in the source code should be placed in this directory. Do not place the top level directory. (2) Its subdirectory tests/ holds unit test code, and (3) The entrance of the program is preferably named main.py .
    3. docs/: Store some documents.
    4. setup.py: Install, deploy, and package the scripts.
    5. requirements.txt: A list of external Python packages that store software dependencies.
    6. README: Project description file.
About the content of the Readme

The goal is to briefly describe the project's information so that the reader can quickly understand the project.

It needs to illustrate several things:

    1. Software positioning, the basic functions of the software.
    2. How to run your code: Installation environment, startup commands, and so on.
    3. Brief instructions for use.
    4. Code directory structure Description, more detailed can explain the basic principles of the software.
    5. FAQ description

Python path: Day04---python basics 4

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.