Python编程细节(二)

来源:互联网 发布:淘宝网保障基金 编辑:程序博客网 时间:2024/06/06 19:33

字符串和文本

1.使用正则来拆分分隔符不一致的字符串

import rere.split(r'[;,\s]',str)

2.在筛选文件拓展名、URL协议的时候,使用str.startswith()或者str.endswith()来检查字符串的开头或者结尾

any(name.endswith('.py') for name in filesnames

3.从字符串中去掉不需要的字符

默认情况下是去除空格符号

strip()lstrip()rstrip()

4.以固定的列数重新格式化文本

import textwraptextwrap.fill(s, number)

数字

1.如果期望得到更高精度的小数运算,可使用decimal模块,但是性能会因降低

from decimal import Decimal

2.format()函数可以使数字进行格式化输出

# 以2位小数点进行输出format(x, '0.2f')# 以二进制进行输出format(x, 'b')

3.不同进制数字间的转换

二进制: bin()
八进制: oct()
十六进制:hex()

4.fractions模块来处理分数的计算

from fractions import Fractionx = Fraction(1,2)

5.随机选择

import random# 从随机序列中随机挑选元素values = [1, 2, 3, 4, 5]random.choice(values)# 从随机序列中随机挑选N个元素random.sample(values, N)# 打乱原序列中元素的顺序random.shuffle(values)# 产生随机整数random.randict(0,10)# 产生0到1之间均匀分布的浮点数random.random()

日期和时间

1.使用dateutil模块可以补充datetime模块中月份的缺失

from datetime import datetimefrom dateutil.relativedelta import relativedeltaa = datetime(2017, 1, 1)a_plus = a = relativedelta(months=+1)

2.字符串和日期的转换

字符串转日期

from datetime import datetimetime = datetime.strptime(str, 'str_format')

迭代器和生成器

1.reversed()可以实现反向迭代

2.permutations()可以迭代所有可能的组合,用conbinations()不考虑顺序进行迭代

from itertools import permutationsfrom itertools import combinations

3.enmuerate()对列表以索引-值的形式进行迭代

4.zip()可以实现同时迭代多个序列

整个迭代的长度和元素最少的那个列表一样

**5.利用chain()在不同的容器中进行迭代

from itertools import chaina = [1,2,3]b = [4,5,6]for x in chain(a,b)    ...

6.合并多个有序序列并迭代

import headqfor c in headq.merge(a,b)    ...

文件和IO

1.将输出文件重新定向到一个文件中

with open('somefile.txt','rt) as f:    print('Hello World',file=f)

2.以不同的分隔符进行打印

print(1,2,3, sep=',')

3.用os.path来处理文件路径

import os# 获取文件路径最后一部分内容os.path.basename(path)# 获取文件路径内容os.path.dirname(path)# 文件路径连接os.path.join(path1, path2)# 检测文件是否存在os.path.exists(path)