【问题标题】:python string strip weird behavior [duplicate]python字符串剥离奇怪的行为[重复]
【发布时间】:2019-01-17 07:37:25
【问题描述】:

我有这种字符串剥离行为有什么原因吗?这是一个错误还是我错过了一些字符串魔法

# 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'

【问题讨论】:

标签: python string python-2.7 strip


【解决方案1】:

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

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

string.rstrip(s[, chars]) 返回删除了尾随字符的字符串副本。如果省略 chars 或 None,则删除空白字符。如果给定而不是 None,chars 必须是字符串; 字符串中的字符将从调用此方法的字符串末尾删除

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2011-10-07
    • 2019-04-11
    • 2019-11-20
    • 2018-07-27
    相关资源
    最近更新 更多