gpt4 book ai didi

python 字符串剥离奇怪的行为

转载 作者:行者123 更新时间:2023-12-01 09:09:33 25 4
gpt4 key购买 nike

我出现这种字符串剥离行为是否有原因?这是一个错误还是我缺少一些字符串魔法

# THIS IS CORRECT
>>> 'name.py'.rstrip('.py')
'name'


# THIS IS WRONG
>>> 'namey.py'.rstrip('.py')
'name'

# TO FIX THE ABOVE I DID THE FOLLOWING
>>> 'namey.py'.rstrip('py').rstrip('.')
'namey'

最佳答案

这是因为 str.rstrip() 命令删除每个尾随字符,而不是整个字符串。

https://docs.python.org/2/library/string.html

string.rstrip(s[, chars]) Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

This also generates same result
>>> 'nameyp.py'.rstrip('.py')
'name'

你可以尝试str().endswith

>>> name = 'namey.py'
... if name.endswith('.py'):
... name = name[:-3]

>>> name
'namey'

或者只是str().split()

>>> 'namey.py'.split('.py')[0]
'namey'

关于python 字符串剥离奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51773772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com