Python字符串strip函数作用

Python 中的 strip()、lstrip() 和 rstrip() 是字符串(str)类型的内置方法,用于去除字符串中指定字符(默认为空白字符)的副本。它们返回处理后的新字符串,原字符串保持不变。

1. strip([chars])

  • 作用 :移除字符串 开头和结尾 指定的字符。
  • 参数 chars(可选):指定要去除的字符集合(一个字符串,其中的每个字符都会被去除)。如果不提供 chars,则默认去除空白字符(空格、换行 \n、制表符 \t 等)。
  • 示例 :

python

复制代码
s = "  hello world  \n"
复制代码
print(s.strip())          #输出:"hello world"(去掉了两端的空格和换行)
复制代码
复制代码
t = "***hello***world***"
复制代码
print(t.strip('*'))       #输出:"hello\*\*\*world"(只去掉开头和结尾的\*,中间的保留)

2. lstrip([chars])

  • 作用 :仅移除字符串 开头 指定的字符。
  • 参数 chars 含义同上,默认为空白字符。
  • 示例 :

python

复制代码
s = "  hello world  "
复制代码
print(s.lstrip())         #输出:"hello world "(去掉了开头的空格,结尾保留)
复制代码
复制代码
t = "www.example.com"
复制代码
print(t.lstrip('w.'))     #输出:"example.com"(去掉开头所有'w'和'.',直到遇到'e')

3. rstrip([chars])

  • 作用 :仅移除字符串 结尾 指定的字符。
  • 参数 chars 含义同上,默认为空白字符。
  • 示例 :

python

复制代码
s = "  hello world  "
复制代码
print(s.rstrip())         #输出:" hello world"(去掉了结尾的空格,开头保留)
复制代码
复制代码
t = "filename.txt"
复制代码
print(t.rstrip('.txt'))   #输出:"filename"(去掉结尾的".txt")
相关推荐
weixin_440730501 分钟前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
天赐范式16 分钟前
天赐范式第181天:让视图开始切换——PBFT视图切换与从safety到liveness的跨越
python·pbft·数字生命·天赐范式·动态运行时·拜占庭容错
sugarzhangnotes26 分钟前
【无标题】
开发语言·人工智能·python
geovindu29 分钟前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
weixin_447195291 小时前
【无标题】
pytorch·python
迅猛龙办公室1 小时前
Python实现简单的人名对话
python
阿坨1 小时前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
老歌老听老掉牙2 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
周杰偷奶茶2 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
happylifetree2 小时前
Python18(补充):练习
python