慎用Python的strip、rstrip、lstrip去除字符串首尾字符

项目里需要对字符进行处理,将字符串结尾的’_all’去掉,果断写出代码

>>> string.rstrip('_all')

一切貌似正常
但不正常的现象出现了

>>> 'xxxxxl_all'.rstrip('_all')

输出结果竟然是:

xxxxx

而不是我们期望的

xxxxxl

所以,这是怎么回事呢?
查了一下官方文档:
https://docs.python.org/3/library/stdtypes.html#str.rstrip
但也没发现有什么规律

在群里问了一下,大神的解释是:
在这里插入图片描述

发现文档中说去除字符首尾特定字符的方法为:removeprefix和.removesuffix
但这两个方法都是3.9版才开始有的。
如果不想换环境,也可以自己写个方法:

def remove_prefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    return text
def remove_suffix(text, suffix):
    if text.endswith(suffix):
        return text[:-len(suffix)]
    return text

参考:https://stackoverflow.com/a/16891418

### Python中`strip()`、`rstrip()`和`lstrip()`的用法及区别 #### 1. `strip(chars)` `strip(chars)` 方法用于删除字符串 **首尾** 所有属于 `chars` 的字符,直到遇到第一个不属于 `chars` 的字符为止。如果未提供 `chars` 参数,则默认去除空白字符(如空格、换行符 `\n` 和制表符 `\t` 等)。 示例代码: ```python s = " hello world! " print(s.strip()) # 去除首尾空格,输出:"hello world!" s = "...www.example.com..." print(s.strip('.w')) # 去除首尾的 '.' 和 'w' 字符,输出:"example.com" ``` 注意:当指定多个字符作为参数时,这些字符会被视为集合而非顺序匹配[^5]。 --- #### 2. `lstrip(chars)` `lstrip(chars)` 方法仅删除字符串 **左侧** 属于 `chars` 的字符。同样地,如果没有提供 `chars` 参数,则默认去除左侧的空白字符。 示例代码: ```python s = " hello world!" print(s.lstrip()) # 去除左侧空格,输出:"hello world!" s = "000123abc000" print(s.lstrip('0')) # 去除左侧的 '0' 字符,输出:"123abc000" ``` --- #### 3. `rstrip(chars)` `rstrip(chars)` 方法仅删除字符串 **右侧** 属于 `chars` 的字符。如果不提供 `chars` 参数,则默认去除右侧的空白字符。 示例代码: ```python s = "hello world! " print(s.rstrip()) # 去除右侧空格,输出:"hello world!" s = "000123abc000" print(s.rstrip('0')) # 去除右侧的 '0' 字符,输出:"000123abc" ``` --- #### 总结对比 | 方法 | 删除位置 | 默认行为 | 是否修改原字符串 | |------------|--------------|-----------------------------|------------------| | `strip()` | 首尾 | 去除空白字符 | 否 | | `lstrip()` | 左侧 (开头) | 去除左侧空白字符 | 否 | | `rstrip()` | 右侧 (结尾) | 去除右侧空白字符 | 否 | 以上三种方法都不会改变原始字符串的内容,而是返回一个新的字符串副本[^4]。 --- #### 实际应用案例 以下是一个综合使用的例子: ```python str1 = " I love you three thousand times!!! " # 使用 strip() 去除首尾空格后再去除感叹号 result = str1.strip().rstrip('!').rstrip() print(result) # 输出:"I love you three thousand times" # 使用 lstrip() 去除左侧特定字符 url = "https://www.google.com/" clean_url = url.lstrip("htps:/.") print(clean_url) # 输出:"www.google.com/" # 使用 rstrip() 去除右侧特定字符 file_name = "document.txt.tmp.bak" base_name = file_name.rstrip(".tmp.bak") print(base_name) # 输出:"document" ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值