Python编程细节(二)

xiaoxiao2021-02-28  112

字符串和文本

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

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

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

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

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

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

strip() lstrip() rstrip()

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

import textwrap textwrap.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 Fraction x = 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 datetime from dateutil.relativedelta import relativedelta a = datetime(2017, 1, 1) a_plus = a = relativedelta(months=+1)

2.字符串和日期的转换

字符串转日期

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

迭代器和生成器

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

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

from itertools import permutations from itertools import combinations

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

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

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

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

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

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

import headq for 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)
转载请注明原文地址: https://www.6miu.com/read-22752.html

最新回复(0)