首页 > 其他 > 详细

常用的字符串处理方法

时间:2017-04-10 20:18:51      阅读:137      评论:0      收藏:0      [点我收藏+]

一、拆分含义多种分隔符的字符串

‘‘‘第一种方法:str.split()处理一个分隔符‘‘‘
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]

s = asas1?ds%jsd,sd|
print mySplit(s, ?%,|)
‘‘‘第二种利用则正,re.split()‘‘‘ import re s = asas1?ds%jsd,sd| print re.split(r[?%,|]+, s)

二、判断以‘a’开头以‘b’结尾的字符串

使用str.startswith()和str.endswith()
import os,stat

l = os.listdir(.)

l1 = [x for x in l if x.startswith(3-3) and x.endswith((.py, .csv))]
print l1

 

三、调整字符串文本格式

使用re.sub()方法

import re
s = 2017-03-10 19:51 chanage type of time
print re.sub(((?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})), r\g<month>/\g<day>/\g<year>, s)

 

四、将多个字符串拼接成一个字符串

‘‘‘第一种方法‘‘‘
s1 = abc
s2 = cdf
s = s1 + s2

‘‘‘第一种方法,使用jion()‘‘‘

l = [abc, 123, 45, xyz]

s = ‘‘.join((str(x) for x in l))

print s

 

五、字符串左、右、居中对齐

s = abc
‘‘‘第一种方法:使用str.ljust(),str.rjust(),str.center()‘‘‘
l = s.ljust(10)
r = s.rjust(10)
c = s.center(10)

‘‘‘第二种方法:使用format‘‘‘
lf = format(s, <20)
rf = format(s, >20)
cf = format(s, ^20)

print l, len(l)
print r, len(r)
print c, len(c)
print -*30
print lf, len(lf)
print rf, len(rf)
print cf, len(cf)

 

六、去掉字符串中不需要的字符

s1 = ---abcd==-=
s2 = \tab\tcsd\t
s3 = \tab\tcsd\t35\r

‘‘‘第一种‘‘‘
print s1.strip(-=)
print s1.lstrip(-=)
print s1.rstrip(-=)

‘‘‘第二种‘‘‘
print s2.replace(\t, ‘‘)

‘‘‘第三种‘‘‘
import re

print re.sub([\t\r]], ‘‘, s3)
print s3.translate(None, \t\r)

 

常用的字符串处理方法

原文:http://www.cnblogs.com/misslin/p/6689968.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!