Python技巧:字符串处理

Welcome To My Blog

一.拆分含有多种分隔符的字符串

  1. 使用.split()
    注意list.extend()
    append是把整个扩充列表作为一个元素追加到列表最后,而Extend则是把每个元素都作为一个独立的元素扩充到原来的列表
s = 'liio;15176|0.0\\0.0,522,65,228,72:p|ts/11+R+'
def mySplit(s,ds):
    res = [s]
    for i,d in enumerate(ds):
        l = []
        #!!如果分割中途有个分隔符在元素的末尾,则会分割出一个空元素
        #list.extend(sequence) 把一个序列seq的内容展平后添加到列表中
        map(lambda x:l.extend(x.split(d)),res) 
        # print '第%s次分割结果(分割符为%s):'%(i+1,d),l
        res = l
    #当x非空时返回
    return [x for x in res if x]
new = mySplit(s,';|\\.+,,/')
print 'new[] = ',new
  1. 使用正则表达式re.split()
#方案二  使用正则表达式
import re
s = 'liio;15176|0.0\\0.0,522,65,228,72:p|ts/11+R+'
#def split(pattern, string, maxsplit=0, flags=0)
#Split the source string by the occurrences of the pattern,
#returning a list containing the resulting substrings
#[]中的每个字符都可作为分割符
q = re.split(r'[;|\\.+,,/]+',s)
print q

两种方法对比: s.split()速度更快,但是不能处理多个分割符; 推荐使用正则表达式

二.判断字符串a是否以字符串b开头或结尾

不仅可以用来处理文本文件,还可以处理磁盘中的文件,筛选出所需的文件类型

import os,stat
f = os.listdir('ceshi/')
print f
s = f[0]
'''
def endswith(self, suffix, start=None, end=None)
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try. 要求是元组!!不能用list
'''
# print s.endswith(('.sh','.py'))
for name in os.listdir('ceshi/'):
    if name.endswith(('.sh','.py')):
        print name

#修改文件权限前要先查看文件权限,用stat
print os.stat('ceshi/a.sh')
print os.stat('ceshi/a.sh').st_mode
#先把权限代码转换成八进制
#666分别是user,group,others的权限值
print oct(os.stat('ceshi/a.sh').st_mode)
os.chmod('ceshi/a.sh',os.stat('ceshi/a.sh'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值