Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/18723580/python-rstrip-one-exact-string-respecting-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...