拆分含有多个分隔符的字符串
示例:单分隔符推荐使用split(),多分隔符推荐使用正则表达式的re.split()
1 # 拆分含有多个分隔符的字符串
2
3 # 只有一个分隔符可用 s.split()
4
5 s = 'abcde,fghij;klmnop|qrstu\tvwxyz'
6
7 # 方法1、 一般方法
8 def my_split(s, seps):
9 res = [s]
10 for sep in seps:
11 t = []
12 list(map(lambda ss: t.extend(ss.split(sep)), res))
13 res = t
14 return res
15 print(my_split(s, ',;|\t'))
16
17 # 方法2、 用于锻炼思维,不适合实战
18 from functools import reduce
19 my_split2 = lambda s, seps: reduce(lambda li, sep: sum(map(lambda ss: ss.split(sep), li), []), seps, [s])
20 print(my_split2(s, ',;|\t'))
21
22 # 方法3、 正则表达式 - 推荐
23 import re
24 my_split3 = re.split('[,;\t|]+', s)
25 print(my_split3)
判断字符串的开头或结尾
示例:
1 # 判断字符串的开头、结尾
2
3 # str.startswith() str.endswith()
4 # 多个匹配时参数使用元组
5
6 str1 = 'aaabbbcccdddeeefffgg'
7 print(str1.startswith("a")) # 输出 True
8 print(str1.startswith("g")) # False
9 print(str1.endswith("a")) # 输出 False
10 print(str1.endswith("g")) # True
调整文本格式:
示例:
1 # 如何调整文本中的文本格式,如给日期换个格式
2
3 # 如某日志格式 2022-03-17 23:25:00 xxxxxxxxxxxxxxxxxx
4
5 import re
6
7 s = '2022-03-17 23:25:00 xxxxxxxxxxxxxxxxxx'
8 # \d是数字,{4}是四位,\d{4}是4位数字;(\d{4})用组括号起来,替换的时候就可用\组号(\3)使用了
9 res = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\3/\2/\1', s)
10 print(res) # 17/03/2022 23:25:00 xxxxxxxxxxxxxxxxxx
11
12 # 如果要替换的地方多,可用用名称代替组号
13 res = re.sub(r'(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})', r'\g<d>/\g<m>/\g<y>', s)
14 print(res)
拼接多个字符串成一个大的
示例:
1 # 拼接多个字符串成一个大的字符串
2
3 # 方法1、使用 ”+“进行拼接
4
5 s1 = 'abc'
6 s2 = '123'
7 print(s1 + s2) # abc123
8 print(s1.__add__(s2)) # abc123
9 print(s2.__add__(s1)) # 123abc
10
11 li = ['ab', 'cd', 'ef', 'ghi', 'jkl', 'mn']
12 s = ''
13 for x in li:
14 s += x
15 print(s) # abcdefghijklmn
16
17 # 方法2、reduce()
18 from functools import reduce
19 res = reduce(str.__add__, li)
20 print(res)
21
22 # 以上方法在创建过程中创建大量多余的字符串,浪费空间
23
24 # 方法3、使用str.join(),一次性创建内存,并一次性连接
25 print(''.join(li)) # abcdefghijklmn
对字符串进行左右居中对齐
示例:
1 # 对字符串进行左、右、居中对齐
2
3 dict_ = {
4 "Join": 100,
5 "Michael": 80,
6 "Ello": 22,
7 "Summery": 88,
8 "Christoper": 70
9 }
10
11 # 方法1、使用字符串的str.ljust(), str.rjust(), str.center()
12 max_len = max(map(len, dict_.keys()))
13 for k, v in dict_.items():
14 print(k.ljust(max_len), ":", v)
15 """
16 输出
17 Join : 100
18 Michael : 80
19 Ello : 22
20 Summery : 88
21 Christoper : 70
22 """
23
24 # 方法2、python内置函数 左对齐10位:format(s, '<10'),右对齐10位:format(s, '>10'),居中对齐10位:format(s, '^10')
25 # 用其他符号补齐 format(s, '*<10') abc*******
26 # format除了字符串,还可以是数字
27 print(format(123, '+')) # 加号代码显示符号,,输出+123
28 print(format(-123, '+')) # -123
29 print(format(-123, '>+10')) # ' -123'
30 print(format(-123, '=+10')) # ’- 123‘
31 print(format(-123, '0=+10')) # -000000123
32 print(format(123, '*=10')) # *******123
剔除字符串中不要的字符
示例:
1 # 去掉字符串中不需要的字符
2
3 # 方法1、strip() lstrip() rstrip()
4
5 # 方法2、 先切片,再“+”拼接
6 # s = 'abc:123'
7 # s[:3] + s[4:]
8
9 # 方法3、replace() 或 re.sub() 删除任意字符串
10 print(' abc def aaa'.replace(' ','')) # abcdefaaa
11 import re
12 print(re.sub('[ \t\n]+', '', ' \t abd \n hihi \t')) # abdhihi
13 print(re.sub('\s+', '', ' \t abd \n hihi \t')) # abdhihi
14
15 # 方法4、字符串的translate(),可用同时删除多种不同的字符
16 s0 = 'abcd1234'
17 print(s0.translate({ord('a'): 'X', ord('b'): 'Y', ord('c'): 'Z'})) # XYZd1234 ord() 转Unicode
18 print(s0.translate(s0.maketrans('abcd', 'XYZK'))) # XYZK1234 替换的位置要对准
19 print(s0.translate({ord('a'): None})) # 把字符串替换成None,相当于删掉这个字符串
27 s2 = 'hello python\r\n'
28 print(re.sub('\s+', '', s2))
29
30
31 s3 = 'wǒ zài xué xí jì suàn jī yǔ yán ' # 字符串是在线转换的,这里用combining判断并非是组合判断
32 import unicodedata
33 # unicodedata.combining() # 判断字符串是否为组合字符
34 res = s3.translate(dict.fromkeys([ord(c) for c in s3 if unicodedata.combining(c)]))
35 print(res) # 输出