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*

 

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