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*
關於python去掉空格常用方式有哪些,環球青藤小編就和大家分享到這裏了,學習是永無止境的,學習壹項技能更是受益終身,所以,只要肯努力學,什麽時候開始都不晚。如果您還想繼續了解關於python編程的學習方法及素材等內容,可以點擊本站其他文章學習。