python中strip和lstrip和rstrip

本文详细介绍了Python中字符串strip方法的使用,包括默认删除空白字符、指定字符删除以及lstrip和rstrip的用法,帮助读者掌握字符串处理技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

strip指删除一个字符的前导和后缀字符

情况1.
如果strip()的参数为空,那么会默认删除字符串头和尾的空白字符(包括\n,\r,\t这些)。

a="\rabbcd123\n"
b=a.strip()
print(b)

abbcd123

情况2.
指定单个参数,会删除前导和后缀cc

a="cchdmccujcc"
b=a.strip("c")
print(b)

hdmccuj

情况3.
指定参数,传入多个参数,参数会默认分开

a="aabcd123abdacc"
b=a.strip("abcd")
c=a.strip("abc")
print(b)
print(c)

123
d123d

lstrip就是单独指前导,rstrip单独指后缀,用法跟前面基本类似,就不赘述了

### 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" ``` ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值