Python learns some details

Source: Internet
Author: User

Http://www.woodpecker.org.cn:9081/projects/pythontutorial/py2.5/html/tut/tut.html

else if using elif instead

[:] There is a copy
The Python sequence uses ":" to provide a copy to prevent operations such as insertions.
>>> # Measure Some strings:
... a = [' Cat ', ' window ', ' defenestrate ']
>>> for X in a:
... print x, Len (x)
...
Cat 3
Window 6
Defenestrate 12

>>> for X in a[:]: # Make a slice copy of the entire list
... if Len (x) > 6:a.insert (0, X)
...
>>> A
[' Defenestrate ', ' Cat ', ' window ', ' defenestrate ']

a[:] A copy of the original sequence is formed.

Print a function with no return value, printing none

Built-in functions and variable names
Dir () does not list built-in functions and variable names. If you want to list these things, they are defined in the standard module __builtin__:
>>> Import __builtin__
>>> dir (__builtin__)

The PY code has Chinese, the compiler cannot explain, can be added in the file header
#coding: UTF-8
Or
#coding: gb2312

The URLLIB2 is enhanced with urllib and can support HTTP header modification and acquisition.
Urllib2 actually uses the Httplib library to implement functionality.

Use of Httplib:
Import Httplib
Conn=httplib. Httpconnection ("www.baidu99.com")
Conn.request ("GET", "/")
R=conn.getresponse ()
Print R.read ()
The version of print r.version#http is generally http/1.1, so this value is 11
Print R.status#200ok, or 302 redirects, etc.
Print r.getheaders () #获取所有的http头
Print R.getheader ("Content-length") #获取特定的头

Note that if there is a redirect, it will not be automatically transferred to you, will give you back the redirected page content.

urllib2 use:
import urllib2
req = urllib2. Request (' http://www.baidu99.com ')  
try: 
r = Urllib2.urlopen (req)  
except Urllib2. Httperror, e: 
Print e
except Urllib2. Urlerror, e: 
Print e.reason,e.filename,e.errno,e.strerror,e.message
Else:
Print r.geturl ()
Print r.headers.headers
Print r.headers.get (' date ')
Print type (r.headers)
Print dir (r.headers)
If there is a redirect, Then automatically return the final result and automatically handle the redirect.

Python also has iterators
Usually for loop things, you can use an iterator to solve.
for element in [1, 2, 3]:
Print element
for element in (1, 2, 3):
Print element
For key in {' One ': 1, ' One ': 2}:
Print key
For char in "123":
Print Char
For line in open ("MyFile.txt"):
Print Line

With iterators
In the background, the For statement calls ITER () in the container object. The function returns an iterator object that defines the next () method, which accesses the element one at a time in the container. When there are no subsequent elements, next () throws a Stopiteration exception notification for the loop end of the for statement. Here's an example of how it works:


>>> s = ' abc '
>>> it = iter (s)
>>> it
<iterator Object at 0x00a1db50>
>>> It.next ()
A
>>> It.next ()
' B '
>>> It.next ()
C
>>> It.next ()

Traceback (most recent):
File "<stdin>", line 1, in?
It.next ()
Stopiteration

Understanding the background mechanism of the iterator protocol makes it easy to add iterator behavior to your own class . Defines a __iter__ () method that returns an object with the next () method. If this class already defines next (), then __iter__ () only needs to return self:


Class Reverse:
    "Iterator for looping over a sequence backwards"
    def __ Init__ (self, data):
        self.data = Data
         Self.index = len (data)
    def __iter__ (self):
         return self
    def next:
        If Self.index = = 0:
            raise Stopiteration
        Self.index = self.index-1
         Return Self.data[self.index]

>>> for Char in Reverse (' spam '):
... print Char
...
M
A
P
S


This article is from "Flying Justice Blog" blog, please be sure to keep this source http://xzq2000.blog.51cto.com/2487359/1766861

Python learns some details

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.