>>>sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log filenot found starting a new one
大多脚本的定向终止都使用 sys.exit()。
字符串正则匹配
re 模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
>>>importre >>>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'
如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:
>>>'tea for too'.replace('too','two')'tea for two'
>>>importrandom >>>random.choice(['apple','pear','banana']) 'apple' >>>random.sample(range(100),10)# sampling without replacement [30,83,16,4,8,81,41,50,18,33] >>>random.random()# random float 0.17970987693706186 >>>random.randrange(6)# random integer chosen from range(6) 4
>>>fromurllib.requestimport 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
>>>importsmtplib >>> 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()
>>># 导入了 datetime 模块中的 date 类>>>from datetime import date
>>> now = date.today()# 当前日期>>> now
datetime.date(2023,7,17)>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")'07-17-23. 17 Jul 2023 is a Monday on the 17 day of July.'>>># 创建了一个表示生日的日期对象>>> birthday = date(1964,7,31)>>> age = now - birthday # 计算两个日期之间的时间差>>> age.days # 变量age的days属性,表示时间差的天数21535
>>>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
def average(values):"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""return sum(values)/ len(values)import doctest
doctest.testmod()# 自动验证嵌入测试
def average(values):"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""return sum(values)/ len(values)import doctest
doctest.testmod()# 自动验证嵌入测试