Python 编程骚操作连载(一)- 字符串、列表、字典和集合的处理(Part A)

简介: Python 编程骚操作连载(一)- 字符串、列表、字典和集合的处理(Part A)

一、字符串的处理

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

如何对一个含有多种特殊字符的字符串进行分割处理,比如向下面这种字符串

str = "A&man$;*who/stands|for+noting=will-fall,for%anything"
复制代码

如何去除特殊风格符获取字符串中所有单词的列表?

如果字符串中只包含单一分隔符的话,可以使用字符串对象的 split 方法,该方法的第一个参数就是分隔符,默认是空格。

str = "A man who stands for noting will fall for anything"
str_list = str.split()
print(str_list)
复制代码

执行上述代码,输出结果如下:

['A', 'man', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for', 'anything']
复制代码

针对包含多种分割符的情况下可以连续调用字符串对象的 split 方法,每次处理一种分隔符

str = "A&man$;*who/stands|for+noting=will-fall,for%anything"
# 第一次处理
res = str.split('&')
print(res)
temp = []
list(map(lambda x: temp.extend(x.split('$')), res))
print(temp)
# 第二次处理
res = temp
temp = []
list(map(lambda x: temp.extend(x.split(';')), res))
print(temp)
# 第三次处理
res = temp
temp = []
list(map(lambda x: temp.extend(x.split('*')), res))
print(temp)
复制代码

执行上述代码,输出结果如下:

['A', 'man$;*who/stands|for+noting=will-fall,for%anything']
['A', 'man', ';*who/stands|for+noting=will-fall,for%anything']
['A', 'man', '', '*who/stands|for+noting=will-fall,for%anything']
['A', 'man', '', '', 'who/stands|for+noting=will-fall,for%anything']
复制代码

根据输出结果可以确定,第一次处理是将字符串中的 &,第二次处理掉了 $...。依次类推,可以将代码抽取为一个函数

def split_multi_chars(str, chars):
    res = [str]
    for c in chars:
        t = []
        list(map(lambda x: t.extend(x.split(c)), res))
        res = t
        print(res)
    return res
str_data = "A&man$;*who/stands|for+noting=will-fall,for%anything"
chars = '&$;*/|+=-,%'
print(split_multi_chars(str_data, chars))
复制代码

执行上述代码,输出结果如下:

['A', 'man$;*who/stands|for+noting=will-fall,for%anything']
['A', 'man', ';*who/stands|for+noting=will-fall,for%anything']
['A', 'man', '', '*who/stands|for+noting=will-fall,for%anything']
['A', 'man', '', '', 'who/stands|for+noting=will-fall,for%anything']
['A', 'man', '', '', 'who', 'stands|for+noting=will-fall,for%anything']
['A', 'man', '', '', 'who', 'stands', 'for+noting=will-fall,for%anything']
['A', 'man', '', '', 'who', 'stands', 'for', 'noting=will-fall,for%anything']
['A', 'man', '', '', 'who', 'stands', 'for', 'noting', 'will-fall,for%anything']
['A', 'man', '', '', 'who', 'stands', 'for', 'noting', 'will', 'fall,for%anything']
['A', 'man', '', '', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for%anything']
['A', 'man', '', '', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for', 'anything']
['A', 'man', '', '', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for', 'anything']
复制代码

根据要去除的特殊字符组成的字符串,依次去除了目标字符串中的所有特殊字符,但是最终输出的字符串中包含了空字符串,可以通过列表推导式去除

def split_multi_chars(str, chars):
    # 其余代码保持不变
    # 使用列表推导式去除空字符串
    return list(x for x in t if x)
# 其余代码保持不变
复制代码

再次执行上述代码,输出结果如下:

# 其余输出结果与上次一致
['A', 'man', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for', 'anything']
复制代码

除了通过连续调用字符串对象的 split 方法依次去除目标字符串中的特殊字符外,还可以通过正则表达式的 split 方法来去除字符串中的特殊字符。

import re
str = "A&man$;*who/stands|for+noting=will-fall,for%anything"
chars = '&$;*/|+=-,%'
res = re.split(r'[=,&$;*/|+%-]+', str)
print(res)
复制代码

执行上述代码,输出结果如下:

['A', 'man', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for', 'anything']
复制代码

字符串中时间格式的替换

以程序运行过程中生成的日志为例,如果想要替换其中的时间格式应该如何操作?

'Started GET "/students" for 127.0.0.1 at 2022-06-11 01:28:05 +0800'
复制代码

可以使用正则表达式的 sub 方法替换字符串,首先使用正则表达式匹配到时间的内容如年月日等,再调整匹配到的内容的顺序。

import re
log = 'Started GET "/students" for 127.0.0.1 at 2022-06-11 01:28:05 +0800'
res = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', log)
# 给每个组起名
res_01 = re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', r'\g<month>/\g<day>/\g<year>', log)
print(res)
print(res_01)
复制代码

执行上述代码,输出结果如下:

Started GET "/students" for 127.0.0.1 at 06/11/2022 01:28:05 +0800
Started GET "/students" for 127.0.0.1 at 06/11/2022 01:28:05 +0800
复制代码

时间格式已被成功替换为指定的格式。

字符串的拼接

对于字符串拼接来说最常用的方法就是 + 操作符,起始 + 操作符是调用了 str 对象底层的 __add__ 方法实现的拼接,包括其他的操作符如 ><= 等都是调用的底层的以双下划线开头和结尾的方法

str_01 = '234324'
str_02 = 'adcdaf'
print(str_01.__add__(str_02))
print(str.__add__(str_01, str_02))
print(dir(str))
复制代码

执行上述代码,输出结果如下:

37ee32c507c14474be5e4a06244c7147_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

当使用 + 操作符拼接多个字符串时会伴随着大量的字符串的创建和销毁,如果要拼接的字符串非常多,这将会消耗大量的资源,而 str 对象的 join 方法可以更加快速的拼接字符串列表中所有的字符串。

new_str = ' '.join(['A', 'man', 'who', 'stands', 'for', 'noting', 'will', 'fall', 'for', 'anything'])
print(new_str)
复制代码

执行上述代码,输出结果如下:

A man who stands for noting will fall for anything
复制代码

如果要拼接的元素中不只是字符串类型,还包含了其他类型,如数字等,则可以使用生成器表达式,将其他类型元素转换为字符串类型之后再进行拼接。

list_data = ['A', 'man', 'who', 123, 'for', 1345, 'will', 'fall']
new_str = ''.join(str(x) for x in list_data)
print(new_str)
复制代码

执行上述代码,输出结果如下:

Amanwho123for1345willfall
复制代码

推荐使用生成器表达式,不推荐使用列表表达式,列表表达式会返回一个列表


相关文章
|
1天前
|
Python Perl
Python中的字符串分析:判断字符串中是否包含字母
Python中的字符串分析:判断字符串中是否包含字母
7 0
|
1天前
|
C语言 Python
【Python 基础】如何进行字符串插值?
【5月更文挑战第6天】【Python 基础】如何进行字符串插值?
|
1天前
|
存储 监控 Python
python 日期字符串转换为指定格式的日期
python 日期字符串转换为指定格式的日期
10 3
|
1天前
|
存储 Python 容器
Python高级编程
Python集合包括可变的set和不可变的frozenset,用于存储无序、不重复的哈希元素。创建集合可使用{}或set(),如`my_set = {1, 2, 3, 4, 5}`。通过add()添加元素,remove()或discard()删除元素,如`my_set.remove(3)`。
|
1天前
|
数据处理 Python
Python中按指定数量分割列表字符串的方法
Python中按指定数量分割列表字符串的方法
7 1
|
2天前
|
测试技术 Python
Python模块化方式编程实践
Python模块化编程提升代码质量,包括:定义专注单一任务的模块;使用`import`导入模块;封装函数和类,明确命名便于重用;避免全局变量降低耦合;使用文档字符串增强可读性;为每个模块写单元测试确保正确性;重用模块作为库;定期维护更新以适应Python新版本。遵循这些实践,可提高代码可读性、重用性和可维护性。
18 2
|
8天前
|
存储 算法 Python
【亮剑】如何在 Python 中查找两个字符串之间的差异位置?
【4月更文挑战第30天】本文探讨了Python中查找两个字符串差异位置的方法。首先,通过内置函数和基本字符串操作,可以逐个字符比较找到第一个不同位置。其次,利用`difflib`库的`SequenceMatcher`能获取更详细的差异信息。最后,通过实现Levenshtein距离算法,可以计算字符串间的最小编辑距离。根据需求选择合适的方法,能提升代码效率和可读性。
|
21天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
68 0
|
3月前
|
数据处理 Python
Python中字符串、列表、字典常用的拼接方法有哪些?
Python中字符串、列表、字典常用的拼接方法有哪些?
59 1
|
5月前
2-Python字符串和列表
2-Python字符串和列表
15 0