0%

Python小技巧(2)--字符串与文本

字符串与文本----来源于cookbook第二章

记录第二章中比较有意思的部分


其实这一章讲的方法挺多挺杂的,但是日常使用基本就正则和python自带的字符串方法,其他的感觉用不到的样子。

正则的话平时写多了自然就会了,这里就不记录了

字符串开头结尾文本匹配

使用str.startswith()str.endwith()即可。在写文件批处理脚本的时候用得到。

1
2
3
4
5

files = ['a.h','a.c','a.exe']
selected = [file for file in files if file.endswith((".h",".c"))]
print(selected) # ['a.h', 'a.c']

字符串去除首尾不需要的字符

使用str.lstrip()str.rstrip()即可

1
2
3
4
5
6
7

s = '-=-=hellp-=-world-=-=-='
s = s.lstrip("-=")
print(s) # 'hellp-=-world-=-=-='
s = s.rstrip("-=")
print(s) # 'hellp-=-world'

字符串拼接

+:效率最低,但是简单

join:效率高,支持列表等

print(*args,sep=","):容易被遗忘的一种方法

1
2
3
4
5
6
7
8

a = 1
b = 2
c = 3

print(','.join(str(i) for i in [a,b,c])) # 1,2,3
print(a,b,c,sep=",") # 1,2,3

给字符串中变量名做插值

作者在书中提到python没法直接处理字符串插值,并实现了一些复杂的方法,
幸运的是,新版本的python已经直接支持插值了,不需手动去实现了

1
2
3
4
5
6

name = 'book'
price = 10
print(f"{name}' price is {price}") # book' price is 10