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)
阅读全文
0 0
- Python编程细节(二)
- theano 编程细节(二)
- Python编程细节(一)
- Python编程细节(三)
- C++基础::shared_ptr 编程细节(二)
- Python编程(二)
- python二之函数细节
- linux复习杂记(二) linux网络编程中的细节
- python 多线程编程(二)
- python多线程编程(二)
- 《Python编程》笔记(二)
- Python多线程编程(二)
- Python 编程笔记(二)
- python高级编程(二)--网络编程
- (Python编程)扩展模块的细节
- Python线程编程(二)线程同步
- Python核心编程笔记(二)
- python核心编程学习(二)
- http连接网络
- 干货丨大数据时代电子政务面临的机遇和挑战
- 谈一下cookie和session
- hdu 2064 匈牙利算法
- 基于HDFS的spark分布式Scala wordcount程序测试
- Python编程细节(二)
- 学习上的思考
- CI框架常用代码
- NuPlayer介绍
- jupyter notebook选择conda环境
- Logistic Regression的决策超平面
- Java高级篇(四十)------Java IO深入理解
- Hibernate之对象之间的关联操作(cascade与fetch)
- C语言+\microsoft visual studio 10.0\vc\include\cmath(40): error C2059: 语法错误:“;”