← 中文资源

简体中文版本

strip 只修两端,不碰中间

strip 系列从两端删掉属于字符集合的字符,不是删前缀后缀:7.50USD.strip("USD") 会误伤数字场景,真前后缀请用 removeprefix/removesuffix。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

strip: 'deploy notes'
lstrip: 'deploy notes  '
rstrip: '  \t deploy notes'
chars: '7.50'
chars: 'example'
digits: 'logs'
prefix: 2024
suffix: report_2024

实现说明

raw 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——strip:、lstrip:、rstrip:。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件的状态由几个模块级绑定持有:raw。

代码示例

raw = "  \t deploy notes \n "

# strip removes leading and trailing whitespace; the middle is untouched
print("strip:", repr(raw.strip()))
print("lstrip:", repr(raw.lstrip()))
print("rstrip:", repr(raw.rstrip()))

# An argument strips any of those characters, not a prefix or suffix
print("chars:", repr("7.50USD".strip("USD")))
print("chars:", repr("www.example.com".strip("w.moc")))

# Digit sets strip padding: 007 is not a prefix, it is just in the set
print("digits:", repr("007logs".strip("0123456789")))

# For real prefixes and suffixes use removeprefix/removesuffix instead
print("prefix:", "unpaid_2024".removeprefix("unpaid_"))
print("suffix:", "report_2024.csv".removesuffix(".csv"))