一、去掉左边空格
- # 注:为了清晰表示,前后的_代表一个空格
- 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*