python 进阶学习(五) 字符串处理

版权声明:诸葛老刘所有 https://blog.csdn.net/weixin_39791387/article/details/82054019

多种分割符拆分字符串

使用re.split() 方法
使用场景: 对字符串ab,cd|ef\tgh;ijk#mn,|\t;#进行分割

方法1:
# 使用str.split()方法来解决
def mysplit(s, ds):
    """
    s: 是需要拆分的字符串
    ds: 是分隔符,可以是多个
    """
    res = [s]

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

str_list = 'ab,,cd|ef\tgh;ijk#mn'
print (mysplit(str_list, ',|;#\t')) 
方法2:推荐
# 使用正则表达式来分隔
import re
a = re.split(r'[,|;#\t]+', str_list)
print(a)

判断字符串的开始或结尾

使用场景:
1. 判断字符串是否是以http://开始的网址
2. 判断字符串是否是以@163.com结束的邮箱
3. 找出当前目录下所有.py.sh文件

In [1]: import os
In [2]: str_list = ['http://www.zhuge.com', '[email protected]', '[email protected]']

In [3]: [s for s in str_list if s.startswith(('http://'))]
Out[3]: ['http://www.zhuge.com']

In [4]: [s for s in str_list if s.endswith(('@zhuge.com', '@zhugefang.com'))]
Out[4]: ['[email protected]', '[email protected]']

In [5]: [name for name in os.listdir('.') if name.endswith(('.sh', '.py'))]
Out[5]: ['test2.py', 'test3.py']

小结:
关键字: str.startswith()str.endswith()
需要注意的是:如果有多个结果,必须使用元组,不能使用列表.比如:name.endswith(('.sh', '.py'))

调整字符串中文本的格式

使用场景:
1. 日期格式转换, YYYY-MM-DD 转为MM/DD/YYYY格式的
2. 中文格式转换, 二手房:成交数据:住宅 转为二手房住宅成交数据

import re
date_str = '2018-08-25发布新的博客, 2012-08-25没有发'
s = '二手房成交数据:住宅, 新房成交数据:住宅'
print(re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', date_str))
# 等效于下面的这个
print(re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', r'\g<month>/\g<day>/\g<year>', date_str))

print(re.sub(r'(房)(成交数据:)(住宅)', r'\1\3\2', s))

猜你喜欢

转载自blog.csdn.net/weixin_39791387/article/details/82054019