python:rstrip一个确切的字符串,尊重顺序 [英] python: rstrip one exact string, respecting order
问题描述
是否可以使用 python 命令 rstrip
以便它只删除一个确切的字符串而不单独删除所有字母?
这件事发生时我很困惑:
>>>"Boat.txt".rstrip(".txt")>>>'蟒蛇'
我的预期是:
>>>"Boat.txt".rstrip(".txt")>>>'船'
我能否以某种方式使用 rstrip 并遵守顺序,以便获得第二个结果?
您使用了错误的方法.使用 str.replace
代替:
注意:str.replace
将替换字符串中的任何位置.
要仅删除最后一个尾随 .txt
,您可以使用 regular表达:
如果你想要没有扩展名的文件名,os.path.splitext
更合适:
Is it possible to use the python command rstrip
so that it does only remove one exact string and does not take all letters separately?
I was confused when this happened:
>>>"Boat.txt".rstrip(".txt")
>>>'Boa'
What I expected was:
>>>"Boat.txt".rstrip(".txt")
>>>'Boat'
Can I somehow use rstrip and respect the order, so that I get the second outcome?
You're using wrong method. Use str.replace
instead:
>>> "Boat.txt".replace(".txt", "")
'Boat'
NOTE: str.replace
will replace anywhere in the string.
>>> "Boat.txt.txt".replace(".txt", "")
'Boat'
To remove the last trailing .txt
only, you can use regular expression:
>>> import re
>>> re.sub(r"\.txt$", "", "Boat.txt.txt")
'Boat.txt'
If you want filename without extension, os.path.splitext
is more appropriate:
>>> os.path.splitext("Boat.txt")
('Boat', '.txt')
这篇关于python:rstrip一个确切的字符串,尊重顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!