首页 > Python3教程 > Python3常用标准库

Python3 字符串正则、数学库、数据压缩

字符串正则

re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案

import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell python')) #['foot', 'fell']

print(re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')) #cat in the hat

如果是简单的字符串处理,首先考虑字符串方法,因为它们非常简单,易于阅读和调试

print('tea for too'.replace('too', 'two')) #tea for two

数学库

math模块为浮点运算提供了对底层C函数库的访问。

import math

print(math.cos(math.pi / 4)) #0.7071067811865476
print(math.log(1024, 2)) #10.0

random提供了生成随机数的工具

import random

print(random.choice(['apple', 'pear', 'banana'])) #apple
print(random.sample(range(100), 10)) # [2, 73, 27, 20, 13, 63, 94, 53, 81, 1]
print(random.random()) # 0.6690087203104802
print(random.randrange(6)) # random integer chosen from range(6) -- 3

数据压缩

通用的数据打包和压缩模块:zlib,gzip,bz2,zipfile,以及 tarfile

import zlib

s = b'I am learn python'
print(len(s)) #17

t = zlib.compress(s)
print(len(t)) #25

print(zlib.decompress(t)) #b'I am learn python'
print(zlib.crc32(s)) #1658670213

 

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。