處理字符串時經常要定制化去掉無用的空格,python 中要么用存在的常規方法,或者用正則處理
1.去掉左邊空格
string = " * it is blank space test * "
print (string.lstrip())
result:
* it is blank space test *
2.去掉右邊空格
string = " * it is blank space test * "
print (string.rstrip())
result:
* it is blank space test *
3.去掉左右兩邊空格
string = " * it is blank space test * "
print (string.strip())
result:
* it is blank space test *
4.去掉所有空格
有兩種方式
eg1:調用字符串的替換方法把空格替換成空
string = " * it is blank space test * "
str_new = string.replace(" ", "")
print str_new
result:
*itisblankspacetest*
eg2:正則匹配把空格替換成空
import re
string = " * it is blank space test * "
str_new = re.sub(r"\s+", "", string)
print str_new
result:
*itisblankspacetest*
來源: https://blog.csdn.net/qingquanyingyue/article/details/93907224