Python strip 疑问

250 天前
 k1z
>>> a = 'chengyucdntest.okeygame.com_2023090613_5_120.log.gz'
>>> a.strip('.gz')
'chengyucdntest.okeygame.com_2023090613_5_120.lo'
>>> b = 'E384UD843W7GXZ.2023-09-06-09.fce6535e.gz'
>>> b.strip('.gz')
'E384UD843W7GXZ.2023-09-06-09.fce6535e'

如上, 有点无法理解为什么 a.strip('.gz')的值后边会少一个 g

有没有大佬解释一下的?

1212 次点击
所在节点    Python
16 条回复
raysonx
250 天前
strip('.gz')的意思是去除. g z 三个字符中的任意一个,当年我初学 python 就踩过这坑。
你的目的可以用 removeSuffix
Kinnice
250 天前
https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip
The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped"
常见新手坑
k2wang
250 天前
Python 文档是这么解释的。
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.

a.strip('gz.')会得到一样的结果,strip 的参数仅表示从开头或结尾移除的字符集
euph
250 天前
Syntax
string.strip(characters)

Parameter Values
Parameter Description
characters Optional. A set of characters to remove as leading/trailing characters
bruce0
250 天前
https://www.v2ex.com/t/969283 前两天 V2 刚讨论过一个 GO 的类似问题
craiiz
250 天前
哈哈,看见有人踩自己踩过的坑真的好开心
复制于 2 楼:
https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip
The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped"
常见新手坑
k1z
250 天前
@raysonx 那去除有顺序吗? 从前还是从后, 还是说只要末尾是这三个字符中的任意一个,那就一直去除下去
Rache1
250 天前
同理,PHP 中的 trim 也是如此
k1z
250 天前
@Kinnice 理解了大佬们
@k2wang 理解了大佬们
@euph 理解了大佬们
@craiiz 理解了大佬们
hertzry
250 天前
可以试试 print(a.replace('.gz', ''))。
k1z
250 天前
@hertzry 嗯。 已经用这个方法了
Azone
250 天前
为什么不用 os.path.splitext ?
k1z
249 天前
@Azone 没用过 - -
julyclyde
249 天前
@hertzry replace 不能确保是开头结尾的位置,也可能是中间
Azone
249 天前
@k1z 你不是想去除文件名的扩展名吗?`os.path.splitext('chengyucdntest.okeygame.com_2023090613_5_120.log.gz')[0]` 不能满足你的需求吗?
k1z
248 天前
@Azone 可以。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/971492

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX