image.png
使用字符串strip()方法
strip()
方法可以用來(lái)去掉字符串開(kāi)始和結(jié)尾的空白,lstrip()
只去掉左邊的曙旭,rstrip()
只去掉右邊的
>>> s = " hello world \t"
>>> s.strip()
'hello world'
>>> s.lstrip()
'hello world \t'
>>> s.rstrip()
' hello world'
默認(rèn)情況下這些方法是去的是空隔符荸镊,但是也指定一個(gè)或多個(gè)字符
t = "----cuzz===="
>>> t.lstrip("-")
'cuzz===='
>>> t.strip("=-")
'cuzz'
>>> t.strip("=-d")
'cuzz'
>>> t.strip("=-dz")
'cu'
使用replace()方法
strip()
方法只能移除兩邊的字符串拜马,不能中間的字符串起作用
str.replace(old, new[, max])
方法把字符串中的old
(舊字符串) 替換成new
(新字符串)单芜,如果指定第三個(gè)參數(shù)max
,則替換不超過(guò)max
次
>>> s = " hello world \t"
>>> s.replace(" ", "")
'helloworld\t'
使用re.sub()方法
str.replace()
只能一次替換一個(gè)字符躁垛,而re.sub()
可以一次替換多次
>>> s = " hello world \t"
>>> re.sub(r"[ \t]", "", s)
'helloworld'
或則使用\s+
表示各種空白字符串
>>> s = " hello world \t"
>>> re.sub(r"\s+", "", s)
'helloworld'
其他方法
對(duì)于更高級(jí)的strip
操作剖毯,應(yīng)該使用translate()
方法,下次遇到在分析