python: rstrip one exact string, respecting order

雨燕双飞 提交于 2019-12-05 08:57:46

问题


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?


回答1:


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



回答2:


Define a helper function:

def strip_suffix(s, suf):
    if s.endswith(suf):
        return s[:len(s)-len(suf)]
    return s

or use regex:

import re
suffix = ".txt"
s = re.sub(re.escape(suffix) + '$', '', s)



回答3:


>>> myfile = "file.txt"
>>> t = ""
>>> for i in myfile:
...     if i != ".":
...             t+=i
...     else:
...             break
... 
>>> t
'file'
>>> # Or You can do this
>>> import collections
>>> d = collections.deque("file.txt")
>>> while True:
...     try:
...             if "." in t:
...                     break
...             t+=d.popleft()
...     except IndexError:
...             break
...     finally:
...             filename = t[:-1]
... 
>>> filename
'file'
>>> 



回答4:


This will work regardless of extension type.

# Find the rightmost period character
filename = "my file 1234.txt"

file_extension_position = filename.rindex(".")

# Substring the filename from first char up until the final period position
stripped_filename = filename[0:file_extension_position]
print("Stripped Filename: {}".format(stripped_filename))


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!