What is the best way to remove the last bit of a string, following a certain recognized pattern? For example:
s = 'some Strings-and-stuff - SomeOther Strings-and-stuff - TAke.THis last -part away.txt'
will return:
'some Strings-and-stuff - SomeOther Strings-and-stuff'
when operated on by some function which looks for the pattern '-' and removes the last string after the last ' - ' occurs.
EDIT: The answer was given to be:
new_string = ' - '.join(s.split(' - ')[0:-1])
Other things I tried:
>>> re.sub(r'(.*) - ', '', s[::-1])[::-1]
'some Strings-and-stuff'
Using the suggested .split() function, I can get the output by this:
>>> p = s.split(' - ')
>>> p.pop()
'TAke.THis last -part away.txt'
>>> ' - '.join(p)
'some Strings-and-stuff - SomeOther Strings-and-stuff'
It works, but the other suggested answer is a better way to get rid of the non one liner pop() or del function.
' with a space on either side of the-. Everything past the last '- `' is deleted.