python高级技巧(二)

字符串处理技巧

拆分字符串

# coding=utf-8
import re

s1 = "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-8
import os

path = './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 re
filename = './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 re

s = '-----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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值