python高级技巧(二)
来源:互联网 发布:url中的端口号 编辑:程序博客网 时间:2024/06/03 21:47
字符串处理技巧
拆分字符串
# coding=utf-8import res1 = "a b c d e f g h i j k"res1 = s1.split()print(res1)s2 = 'a;b|c,d-e|f\tg;h,i&j k'res2 = re.split('[-,;|\t& ]', s2)print(res2)
endswith() startwith()
# coding=utf-8import ospath = './data'files = os.listdir(path)py = filter(lambda s: s.endswith('.py'), files)sh_c = filter(lambda x: x.endswith(('.sh', '.c')), files)print(list(sh_c))
调整字符串顺序
2017-10-28 ==》10/28/2017
import refilename = './data/log'with open(filename) as f: for line in f: #rline = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', line[:100]) rline = re.sub('(?P<year>\d{4})-(?P<mouth>\d{2})-(?P<day>\d{2})', r'\g<mouth>/\g<day>/\g<year>', line[:100]) print(rline)
拼接字符串
# str+str 加号就不多说了,元素多了,他就需要不停的创建释放对象,开销太大# [x for x in something] 叫做“列表解析”,内存开销很大# (x for x in something) 叫做“生成器” ,内存占用小,对于大文件很有效aa = ['h', 'el', 'lo']resaa = ''.join(aa)bb = ['q', 1, '2', 'qwe']resbb = ''.join(str(x) for x in bb)print(resaa, resbb)
对齐
person = { 'name': 'xiaoming', 'age': '23', 'sex': 'male', 'good_friends': 'a,b,v', 'hobby': 'socker'}w = max(map(len, person.keys()))# ljust rjust center 左右上对齐for k, v in person.items(): print(k.ljust(w), ':', v)# < > ^ 左右上对齐# for k, v in person.items():# print(format(k, '<3'), v)
去掉不要的字符串
import res = '-----hello-----world-----'print(s.lstrip('='))print(s.rstrip('='))print(s.strip('='))s = '123-qwe'print(s[:3]+s[4:])print(s.replace('-', ''))s2 = 'a;b|c,d-e|f\tg;h,i&j k's2 = re.sub('[-,;|\t& ]', '', s2)print(s2)
阅读全文
1 0
- python高级技巧(二)
- Python高级技巧(一)
- Python技巧(二)
- (二)python高级特性
- FireFox高级使用技巧系列(二)
- php高级技巧大放送(二)
- linux高级技巧:heartbeat+lvs(二)
- linux高级技巧:rsync同步(二)
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python 高级编程技巧
- 冒泡排序
- HDU 6170 Two strings (dp)
- lua和C++交互
- 插入排序
- Spring源码阅读(一)——整体结构
- python高级技巧(二)
- 单链表的基本操作
- 机器学习学习笔记之三:朴素贝叶斯
- 【性能测试】-Loadrunner性能测试结果分析(五)
- ubuntu nginx配置https服务器
- logback.xml配置示例
- 最长什么什么子序列进阶(xym的hu测)
- mediaplayer 播放例子
- jquery_selector03