Python技巧(二)字符串

来源:互联网 发布:编译arm linux内核4.5 编辑:程序博客网 时间:2024/05/22 04:48

1.如何拆分含有多种分隔符的字符串

def mysplit(s,ds):    res = [s]    for d in ds:        t = []        map(lambda x:t.extend(x.split(d)),res)        res = t    return [x for x in res if x]

使用正则表达式的re.split()

import rere.split(r'[,;\t]+',s)

2.如何判断字符串a是否以字符串b开头或结尾
使用字符串的str.startwith()和str.endwith()

实例编写程序给所有的.sh,.py结尾的文件加上可执行权限

import os,stat
os.listdir(‘.’)
s=’1.py’
s.endswith(‘.py’)

l = [name for name in os.listdir('.') if name.endswith(('.sh','.py'))]for x in l:    os.chmod(x,os.stat('1.py').st_mode|stat.S_IXUSR)

3.如何调整字符串中文件的格式

实例时间格式2017-1-23改为1/23/2017
使用正则表达式的re.sub()方法做替换

cat /var/log/dpkg.loglog = open('/var/log/dpkg.log').read()import reprint re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',r'\g<month>\g<day>\g<year>',log)

4.如何将多个字符串拼接为一个大的字符串

s = ''p=['1','2','3','4']for pl in p:    s +=plstr.__add__(str1,str2)':'.join(['1','2','3'])l=['a',123,'b']''.join([str(x) for x in l])

5.如何对字符串进行左,右,居中对齐
(1)使用字符串的str.ljust(),str.rjust(),str.center()进行左右居中对齐

s='abc's.ljust(20,'=')s.rjust(20,'=')s.center(20)

(2)使用format()方法,传递类似’<20’,’>20’,’^20’参数完成同样任务

s='abc'format(s,'<20')format(s,'>20')format(s,'^20')
w = max(map(len,d.keys()))for k in d:    print k.ljust(w),':',d[k]

6.如何去掉字符串中不需要的字符
(1)字符串strip(),lstrip(),rstrip()方法去掉字符串两端字符
(2)删除单个固定位置的字符,可以使用切片+拼接的方式
(3)字符串的replace()方法或正则表达式re.sub()删除任意位置字符
(4)字符串translate()方法,可以同时删除多种不同字符

(1)

    s = '  abc  123   '    s.strip()    s.lstrip()    s.rstrip()    s = '---sbc+++'    s.strip('-+')

(2)

    s = 'abc:123'    s[:3]+s[4:]

(4)

    s = '\tabc\t123\txyz'    s.replace('\t','')    s = '\tabc\t123\txyz'    import re    re.sub('[\t\r]','',s)

(5)

     s = 'abc1230321xyz'    import string     s.translate(string.maketrans('abcxyz','xyzabc'))
0 0