字符串的操作训练

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

zero, one, two, three, fous, five, six, seven, eight, nine = range(10)
"""
Author:Cairo
"""
'''
实际案例:
    我们要把某个字符串依据分隔符号拆分不同的字段,
    该字符串包含多种不同的分隔符,例如:
    s='ab;cd|ef+hi,/ds\aef;sdfe.usad\txyz'
'''
'''
解决方案:
    方法一:连续使用是str.split()方法,每次处理一种分隔符号。
    方法二:使用正则表达式的re.split()方法,一次性拆分字符串。
'''
# def mysplit(s,ds):
#     res = [s]
#     for i in ds:
#         t = []
#         map(lambda x:t.extend(x.split(i)) , res)
#         res = t
#     return res
s='ab;cd|ef+hi,/ds\tef;sd fe.usad\txyz'
# print(mysplit(s,';|/,.\t'))

# 二:
import re
print(re.split(r'[;|/,.\t+ ]+',s))#方括号内的是切割符号,方括号外边的+号是一个或者多个
#注意:如果只是切割一个字符串就用s.split(),因为这个比正则快

如何判断字符串是a是否以字符串b开头或结尾

zero, one, two, three, fous, five, six, seven, eight, nine = range(10)
"""
Author:Cairo
"""
'''
使用字符串的str.startswith()和str.endswith(可以多个)方法。
注意:多个匹配时参数使用元组
'''
import os , stat
print(os.listdir('.'))

正则的捕获与替换

zero, one, two, three, fous, five, six, seven, eight, nine = range(10)
"""
Author:Cairo
"""
import re
log = ['2018-05-06','2017-08-06','2016-05-08','2019-01-23']
# for i in log:
#     print(re.sub('(\d{4})-(\d{2})-(\d{2})',r'\1/\2/\3',i))

'''
返回的是一个地址,要看看需求来定了
#使用匿名函数解析
# nima = map(lambda x:re.sub('(\d{4})-(\d{2})-(\d{2})',r'\1/\2/\3',x),log)
# print(nima)
# 使用map+lambda返回地址
# nima = filter(lambda x:re.sub('(\d{4})-(\d{2})-(\d{2})',r'\1/\2/\3',x),log)
# print(nima)
# 使用filter+lambda返回地址
'''

# 列表解析
print([x for x in log if re.sub('(\d{4})-(\d{2})-(\d{2})',r'\1/\2/\3',x)])

'''
:r'\1/\2/\3':替换前面的,捕获组
:r:原始字符串
'''
# 还可以给每个组取名
for i in log:
    print(re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',r'\g<year>/\g<month>/\g<day>',i))

 

posted @ 2018-05-26 16:19  Caionk  阅读(142)  评论(0编辑  收藏  举报