Python之去掉字符串空格(strip)

本文介绍了Python中处理字符串空格的三种方法:strip(), lstrip() 和 rstrip()。通过实例演示了如何使用这些函数去除字符串两端、左端或右端的空格。

正文:


Python去掉字符串空格有三个函数:


strip 同时去掉字符串左右两边的空格;
lstrip 去掉字符串左边的空格;
rstrip 去掉字符串右边(末尾)的空格;

详细解读:


声明:s为字符串,re为要删除的字符序列

  • strip函数:s.strip(re)
    1,用于删除s字符串中开头处、结尾处、位于re删除序列的字符
    2,当re为空时,strip()默认是删除空白符(包括‘\n’,‘\r’,‘\t’,‘’),例如:
>>>a = '    abc'
>>>a.strip()
'abc'
>>>a = '\t\t\nabc'
>>>a.strip()
'abc'
>>>a = '  abc\r\t'
>>>a.strip()
'abc'

3,这里我们说的re删除序列是只要满足re的开头或者结尾上的字符在删除序列内,就能删除掉,比如说:

>>> a = 'abc123'
>>>>a.strip('342')
'abc1'
>>>a.strip('234')
'abc1'

可以看出结果是一样的。

  • lstrip函数:s.lstrip(re),用于删除s字符串中开头处,位于re删除序列中的字符,比如:
>>>a = "    this is string example.....wow!!!   "
>>>a.lstrip()
'this is string example.....wow!!!   '
>>>a = "88888888this is string example....wow!!!8888888"
>>>a.lstrip('8')
'this is string example....wow!!!8888888'
  • rstrip函数:s.rstrip(re),用于删除s字符串中结尾处,位于re删除序列的字符,比如:
>>>a = "    this is string example.....wow!!!   "
>>>a.rstrip()
'    this is string example.....wow!!!'
>>>a = "88888888this is string example....wow!!!8888888"
>>>a.rstrip('8')
'8888888this is string example....wow!!!'

OK!到此结束啦,不知道你了解了没???^-^

Python 中,去除字符串中的空格是一个常见的操作,根据要去除空格类型(前导、后缀、中间、所有)可以使用不同的方法。以下是几种常用的方法及其使用场景。 --- ## ✅ 1. `str.strip()`:去除字符串两端的空格(包括换行符、制表符等) ```python s = " Hello World! " print(s.strip()) # 输出: 'Hello World!' ``` - 适用于去除开头和结尾的空白字符。 - 不会影响字符串中间的空格。 --- ## ✅ 2. `str.lstrip()`:仅去除字符串左侧(开头)的空格 ```python s = " Hello World! " print(s.lstrip()) # 输出: 'Hello World! ' ``` --- ## ✅ 3. `str.rstrip()`:仅去除字符串右侧(结尾)的空格 ```python s = " Hello World! " print(s.rstrip()) # 输出: ' Hello World!' ``` --- ## ✅ 4. `str.replace(" ", "")`:去除所有空格(仅去除空格字符) ```python s = " Hello World! " print(s.replace(" ", "")) # 输出: 'HelloWorld!' ``` - 仅去除普通空格 `' '`,不包括 `\t` 或 `\n`。 - 如果想去除所有空白字符,请使用正则表达式。 --- ## ✅ 5. 使用 `re` 模块去除所有空白字符(包括空格、制表符、换行等) ```python import re s = " Hello \t\n World! " print(re.sub(r'\s+', '', s)) # 输出: 'HelloWorld!' ``` - `\s+` 表示一个或多个空白字符。 - 适用于需要彻底去除所有空白的情况。 --- ## ✅ 6. 使用 `split()` 和 `join()` 去除多余空格并保留单词间单个空格 ```python s = " Hello World! " print(' '.join(s.split())) # 输出: 'Hello World!' ``` - `split()` 默认按任意空白分割成列表。 - `join()` 将列表用单个空格连接起来。 --- ## ✅ 总结对比 | 方法 | 功能 | 是否影响中间空格 | |------|------|------------------| | `strip()` | 去除首尾空格 | ❌ | | `lstrip()` | 去除开头空格 | ❌ | | `rstrip()` | 去除结尾空格 | ❌ | | `replace(" ", "")` | 去除所有空格(仅 `' '`) | ✅ | | `re.sub(r'\s+', '', s)` | 去除所有空白字符(空格、制表符、换行等) | ✅ | | `join(split())` | 去除多余空格,保留单词间单个空格 | ✅ | --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HuaCode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值