>>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings>
>>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat'
如果只需要简单的功能,应该首先考虑字符串方法,因为他们非常简单,易于阅读和调试:
1 2
>>> 'tea for too'.replace('too', 'two') 'tea for two'
>>> from urllib.request import urlopen >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... line = line.decode('utf-8') # Decoding the binary data to text. ... if'EST'in line or'EDT'in line: # look for Eastern Time ... print(line)
<BR>Nov. 25, 09:43:32 PM EST ## 注意第二个例子需要本地有一个在运行的邮件服务器。 >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org', ... """To: jcaesar@example.org ... From: soothsayer@example.org ... ... Beware the Ides of March. ... """) >>> server.quit()
import urllib from urllib.request import Request from urllib.parse import urlencode
url='http://www.xxx.com/login' data={"username":"admin","password":123456} data=urlencode(data)#将字典类型的请求数据转变为url编码 data=data.encode('ascii')#将url编码类型的请求数据转变为bytes类型 req_data=Request(url,data)#将url和请求数据处理为一个Request对象,供urlopen调用 with urlopen(req_data) as res: res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str
print(res)
日期和时间
datetime模块为日期和时间处理同时提供了简单和复杂的方法。
支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。
该模块还支持时区处理:
1 2 3 4 5 6 7 8 9 10 11 12 13
>>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
>>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368
>>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979