zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python 字符串去空格

Python 字符串 空格
2023-06-13 09:11:55 时间

大家好,又见面了,我是你们的朋友全栈君。

一、去除字符串空格,使用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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139949.html原文链接:https://javaforall.cn