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)
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)
nne*_*neo 12
在 Python 3.9 中,作为PEP-616 的一部分,您现在可以使用removeprefix和removesuffix函数:
>>> "Boat.txt".removeprefix("Boat")
>>> '.txt'
>>> "Boat.txt".removesuffix(".txt")
>>> 'Boat'
Run Code Online (Sandbox Code Playgroud)