python:rstrip一个精确的字符串,尊重顺序

ald*_*ado 26 python string strip

是否可以使用python命令,rstrip以便它只删除一个完整的字符串,并不单独收集所有字母?

发生这种情况时我很困惑:

>>>"Boat.txt".rstrip(".txt")
>>>'Boa'
Run Code Online (Sandbox Code Playgroud)

我的期望是:

>>>"Boat.txt".rstrip(".txt")
>>>'Boat'
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式使用rstrip并尊重顺序,以便获得第二个结果吗?

fal*_*tru 32

You're using wrong method. Use str.replace instead:

>>> "Boat.txt".replace(".txt", "")
'Boat'
Run Code Online (Sandbox Code Playgroud)

NOTE: str.replace will replace anywhere in the string.

>>> "Boat.txt.txt".replace(".txt", "")
'Boat'
Run Code Online (Sandbox Code Playgroud)

To remove the last trailing .txt only, you can use regular expression:

>>> import re
>>> re.sub(r"\.txt$", "", "Boat.txt.txt")
'Boat.txt'
Run Code Online (Sandbox Code Playgroud)

If you want filename without extension, os.path.splitext is more appropriate:

>>> os.path.splitext("Boat.txt")
('Boat', '.txt')
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这将替换字符串中的任何位置。 (3认同)
  • 注意,这里的正则表达式是一个过大的杀伤力。仅当分隔符的模式与扩展名匹配时,os.path.splitext才起作用。@nneonneo的解决方案适合所有情况。 (2认同)

nne*_*neo 13

Define a helper function:

def strip_suffix(s, suf):
    if s.endswith(suf):
        return s[:len(s)-len(suf)]
    return s
Run Code Online (Sandbox Code Playgroud)

or use regex:

import re
suffix = ".txt"
s = re.sub(re.escape(suffix) + '$', '', s)
Run Code Online (Sandbox Code Playgroud)

  • 这个 `strip_suffix(s, suf)` 解决方案是这里的最佳答案,因为使用 `.replace()` 的公认解决方案正在用另一种稍微危险的解决方案替换一个稍微危险的解决方案。原始的 `.rstrip` 和 `.replace` 都有可能偶尔返回与 OP 的原始意图相反的结果。我想知道为什么 Python 没有内置这样的东西.. (2认同)

nne*_*neo 12

在 Python 3.9 中,作为PEP-616 的一部分,您现在可以使用removeprefixremovesuffix函数:

>>> "Boat.txt".removeprefix("Boat")
>>> '.txt'

>>> "Boat.txt".removesuffix(".txt")
>>> 'Boat'
Run Code Online (Sandbox Code Playgroud)