我们想去除字符串中不必要的空格时可以使用如下方法:

在这里以str作为例子来演示。在str中前中后三处都有空格。

函数原型:

声明:str为字符串,rm为要删除的字符序列

  • str.strip(rm) : 删除s字符串中开头、结尾处,位于 rm删除序列的字符
  • str.lstrip(rm) : 删除s字符串中开头(左边)处,位于 rm删除序列的字符
  • str.rstrip(rm) : 删除s字符串中结尾(右边)处,位于 rm删除序列的字符
  • str.replace(‘s1’,’s2’) : 把字符串里的s1替换成s2。故可以用replace(’ ‘,”)来去掉字符串里的所有空格
  • str.split() : 通过指定分隔符对字符串进行切分,切分为列表的形式。
  • 去除两边空格:
>>> str = ' hello world '
>>> str.strip()
'hello world'
  • 去除开头空格:
>>> str.lstrip()
'hello world '
  • 去除结尾空格:
>>> str.rstrip()
' hello world'
  • 去除全部空格:
>>> str.replace(' ','')
'helloworld'
  • 将字符串以空格分开:
>>> str.split()
['hello', 'world']
>>>