2022年 11月 6日

Python去掉空格的常用方法

一、去掉左边空格

  1. # 注:为了清晰表示,前后的_代表一个空格
  2. string = " * it is blank space test * "
  3. print (string.lstrip())
  4. #result:
  5. #* it is blank space test *__

二、去掉右边空格

  1. # 注:为了清晰表示,前后的_代表一个空格
  2. string = " *it is blank space test * "
  3. print (string.lstrip())
  4. #result:
  5. #__* it is blank space test *

三、去掉两边空格

  1. # 注:为了清晰表示,前后的_代表一个空格
  2. string = " * it is blank space test * "
  3. print (string.lstrip())
  4. #result:
  5. #* it is blank space test *

四、去掉所有空格

方法一:调用字符串的替换方法把空格替换为空

  1. string = " * it is blank space test * "
  2. str_new = string.replace(" ", "")
  3. print str_new
  4. #result:
  5. #*itisblankspacetest*

方法二:正则匹配把空格替换成空

  1. import re
  2. string = " * it is blank space test * "
  3. str_new = re.sub(r"\s+", "", string)
  4. print str_new
  5. #result:
  6. #*itisblankspacetest*