一、去除字符串空格,使用python的内置方法

1、lstrip:删除左边的空格
这个字符串方法,会删除字符串s开始位置前的空格。

>>> s.lstrip()
'string   '

2、rstrip:删除右连的空格
这个内置方法可以删除字符串末尾的所有空格,看下面演示代码:

>>> s.rstrip()
'    string'

3、strip:删除两端的空格
有的时候我们读取文件中的内容,每行2边都有空格,能不能一次性全部去掉呢,字符符有一个内置的strip()方法可以做到。

>>> s = “   这是一个字符串    ”
>>> s.strip()
'string'

二、python去除字符串中间空格的方法

1、使用字符串函数replace

>>> a = 'hello world'
>>> a.replace(' ', '')
'helloworld'

2、使用字符串函数split

>>> a = ''.join(a.split())
>>> print(a)
helloworld

3、使用正则表达式

>>> import re
>>> strinfo = re.compile()
>>> strinfo = re.compile(' ')
>>> b = strinfo.sub('', a)
>>> print(b)
helloworld