一.拆分含有多种分隔符的字符串
- 使用.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
- 使用正则表达式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'