天天看点

Python3实用编程技巧进阶二

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

s = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz'
# print(s.split('|,;'))
# print(s.split(';'))
"""
['ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz']
['ab', 'cd|efg|hi,jkl|mn\topq', 'rst,uvw\txyz']
"""
#第一种分割
l = map(lambda ss:ss.split('|'),s.split(';'))
# print(list(l))
#[['ab'], ['cd', 'efg', 'hi,jkl', 'mn\topq'], ['rst,uvw\txyz']]




#第二种 通过extend 把多个列表合并为一个
t=[]
tt = map(t.extend,[ss.split('|') for ss in s.split(';')])
print(list(tt))
#[None, None, None]
print(t)
#['ab', 'cd', 'efg', 'hi,jkl', 'mn\topq', 'rst,uvw\txyz']

#第二种 通过extend 把多个列表合并为一个
t2=[]
tt2 = map(t.extend,[map(t2.extend,[ss.split('|') for ss in s.split(';')])])
print(list(tt2))
#[None, None, None]
print(t2)


#第三种通过sum函数 合并多个列表
ttt = sum([ss.split('|') for ss in s.split(';')],[])
print(ttt)
#和map一样的效果
#['ab', 'cd', 'efg', 'hi,jkl', 'mn\topq', 'rst,uvw\txyz']


def my_split(s,seps):
    res = [s]
    for sep in seps:
        t = []
        list(map(lambda ss:t.extend(ss.split(sep)),res))
        res = t
    return res

print(my_split(s,',;|\t'))
#['ab', 'cd', 'efg', 'hi', 'jkl', 'mn', 'opq', 'rst', 'uvw', 'xyz']

#第四种 通过reduce函数特性
from functools import reduce
ddd= reduce(lambda l,sep :sum(map(lambda ss:ss.split(sep),l),[]),',;|\t',[s])
print(ddd)
#['ab', 'cd', 'efg', 'hi', 'jkl', 'mn', 'opq', 'rst', 'uvw', 'xyz']      

2,如果调整字符串中文本的格式

import re
str='2019-11-12 09:23:23 ddddd'
r = re.sub(r'(?P<d>\d{4})-(?P<m>\d{2})-(?P<y>\d{2})',r'\g<m>/\g<d>/\g<y>',str)
print(r)

11/2019/12 09:23:23 ddddd      

3,如何将多个小字符串拼接成一个大字符串

s1 = 'abcdefg'
s2 = '123456'
print(s1+s2)
#abcdefg123456
print(str.__add__(s1,s2))
#abcdefg123456


print("".join([s1,s2]))
#abcdefg123456      

4,如何对字符串进行左中右居中对齐

s = 'abc'
ss = s.ljust(10)
print(ss)
#abc
print(len(ss))
#10

print(s.rjust(10,'*'))
#*******abc
print(s.center(10,'*'))
#***abc****


print(format(s,'*<10')) #abc*******
print(format(s,'*>10')) #*******abc
print(format(s,'*^10')) #***abc****

#+加号标识总输出符号
print(format(123,'+'))#+123 正的
print(format(-123,'+'))#-123  负的
print(format(-123,'>+10'))#      -123
print(format(-123,'=+10'))#-      123
print(format(123,'0=+10'))#+000000123


d= {'lodDist':100.0,'SmallCull':0.04,'DistCull':500.0,'trilinear':40,'farclip':477}
print(max(map(len,d.keys())))
w = max(map(len,d.keys()))
for k,v in d.items():
    print(k.ljust(w),':',v)
    
"""
lodDist   : 100.0
SmallCull : 0.04
DistCull  : 500.0
trilinear : 40
farclip   : 477
"""      
s= '   [email protected]   '
print(s.strip())
print(s.lstrip())
print(s.rstrip())

s= '[email protected]++=='
print(s.strip('=+-'))


s2='abc:123'
print(s2[:3]+s2[4:])#abc123



s3 = '   abc  xyz  '
print(s3.strip()) #abc  xyz

s3 = '\t  abc \t xyz \n'
print(s3.replace(' ',''))#    abc    xyz

import re
print(re.sub('[ \t\n]+','',s3))
#abcxyz
print(re.sub('\s+','',s3))
#abcxyz