Python去掉空格的常用方法

一、去掉左邊空格

# 注:爲了清晰表示,前後的_代表一個空格
string = "  * it is blank space test *  "
print (string.lstrip())


#result:
#* it is blank space test *__

二、去掉右邊空格

# 注:爲了清晰表示,前後的_代表一個空格
string = "  *it is blank space test *  "
print (string.lstrip())


#result:
#__* it is blank space test *

三、去掉兩邊空格

# 注:爲了清晰表示,前後的_代表一個空格
string = "  * it is blank space test *  "
print (string.lstrip())


#result:
#* it is blank space test *

四、去掉所有空格

方法一:調用字符串的替換方法把空格替換爲空

string = "  * it is blank space test *  "
str_new = string.replace(" ", "")
print str_new

#result:
#*itisblankspacetest*

方法二:正則匹配把空格替換成空

import re

string = "  * it is blank space test *  "
str_new = re.sub(r"\s+", "", string)
print str_new

#result:
#*itisblankspacetest*

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章