Python去除字符串前后空格的几种方法
作者:杰瑞26 时间:2021-12-22 02:10:02
其实如果要去除字符串前后的空格很简单,那就是用strip(),简单方便
>>> ' A BC '.strip()
'A BC'
如果不允许用strip()的方法,也是可以用正则匹配的方法来处理。
>>> s1 = ' A BC'
>>> s2 = 'A BC '
>>> s3 = ' A BC '
>>> s4 = 'A BC'
>>> def trim(s):
... import re
... if s.startswith(' ') or s.endswith(' '):
... return re.sub(r"^(\s+)|(\s+)$", "", s)
... return s
>>> trim(s1)
'A BC'
>>> trim(s2)
'A BC'
>>> trim(s3)
'A BC'
>>> trim(s4)
'A BC'
如果也不用正则匹配的话,还可以借助递归函数来去除前后的空格。
>>> s1 = ' A BC'
>>> s2 = 'A BC '
>>> s3 = ' A BC '
>>> s4 = 'A BC'
>>> def trim(s):
... if s[0] == " ":
... return trim(s[1:]) # 如果开首有多个空格的话,递归去除多个空格
... elif s[-1] == " ":
... return trim(s[:-1]) # 如果末尾有多个空格的话,递归去除多个空格
... else:
... return s
>>> trim(s1)
'A BC'
>>> trim(s2)
'A BC'
>>> trim(s3)
'A BC'
>>> trim(s4)
'A BC'
来源:https://blog.csdn.net/Jerry_1126/article/details/87208002
标签:python,字符串,去除空格
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
django实现用户登陆功能详解
2021-03-04 20:19:06
![](https://img.aspxhome.com/file/2023/1/88891_0s.jpg)
JAVA/JSP学习系列之一
2023-06-19 16:44:14
python实现宿舍管理系统
2023-12-28 14:14:27
![](https://img.aspxhome.com/file/2023/7/105747_0s.jpg)
用Python实现读写锁的示例代码
2022-09-19 13:51:01
pandas 添加空列并赋空值案例
2022-12-04 13:48:16
![](https://img.aspxhome.com/file/2023/1/72091_0s.jpg)
js鼠标事件大全
2007-08-13 15:56:00
基于PyQt5制作一个windows通知管理器
2022-10-18 19:28:24
![](https://img.aspxhome.com/file/2023/7/75327_0s.gif)
numpy中的transpose函数中具体使用方法
2023-04-28 23:46:44
![](https://img.aspxhome.com/file/2023/2/81582_0s.png)
python多线程抓取天涯帖子内容示例
2021-03-18 11:56:42
文字的减法
2007-11-06 12:58:00
python Django 创建应用过程图示详解
2022-10-29 03:04:40
![](https://img.aspxhome.com/file/2023/4/67304_0s.png)
Python参数解析器configparser简介
2021-04-22 02:23:31
![](https://img.aspxhome.com/file/2023/1/95781_0s.png)
asp如何生成XML数据
2007-08-20 09:50:00
python中的None与NULL用法说明
2022-01-01 13:59:15
Python NumPy库安装使用笔记
2022-05-20 17:49:56
利用python做数据拟合详情
2023-04-22 15:32:17
![](https://img.aspxhome.com/file/2023/1/103221_0s.png)
Python 基于TCP 传输协议的网络通信实现方法
2023-06-18 22:04:01
![](https://img.aspxhome.com/file/2023/3/89233_0s.jpg)
网马解密大讲堂——网马解密中级篇(Eval篇)
2009-09-16 16:04:00
asp fso删除非空目录的例子
2008-11-26 20:03:00
如何设计具可用性的网页表单?
2010-03-20 21:57:00
![](https://img.aspxhome.com/file/UploadPic/20103/20/01-42s.jpg)