
image.png
使用字符串strip()方法
strip()方法可以用來去掉字符串開始和結(jié)尾的空白,lstrip()只去掉左邊的,rstrip()只去掉右邊的
>>> s = " hello world \t"
>>> s.strip()
'hello world'
>>> s.lstrip()
'hello world \t'
>>> s.rstrip()
' hello world'
默認(rèn)情況下這些方法是去的是空隔符,但是也指定一個或多個字符
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(新字符串),如果指定第三個參數(shù)max,則替換不超過max次
>>> s = " hello world \t"
>>> s.replace(" ", "")
'helloworld\t'
使用re.sub()方法
str.replace()只能一次替換一個字符,而re.sub()可以一次替換多次
>>> s = " hello world \t"
>>> re.sub(r"[ \t]", "", s)
'helloworld'
或則使用\s+表示各種空白字符串
>>> s = " hello world \t"
>>> re.sub(r"\s+", "", s)
'helloworld'
其他方法
對于更高級的strip操作,應(yīng)該使用translate()方法,下次遇到在分析