python 字符串去空格

来源:互联网 发布:海美迪hd600a软件下载 编辑:程序博客网 时间:2024/06/16 05:18

一、去除字符串空格,在Python里面有它的内置方法

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

>>> s.lstrip()'string   '

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

>>> s.rstrip()'    string'

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
0 0
原创粉丝点击