2

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.

4
  • 1
    Split by " - ", remove the last piece and implode the rest. Commented May 6, 2013 at 18:25
  • How is the initial part of the string recognised? Commented May 6, 2013 at 18:26
  • He actually wants two of those parts after the hyphen to be removed. @chase I guess you'd have to provide what kind of pattern you want to remove in order for me to suggest a regular expression for that. Commented May 6, 2013 at 18:32
  • Sorry the pattern to recognize is '` - ' with a space on either side of the -. Everything past the last ' - `' is deleted. Commented May 6, 2013 at 18:34

2 Answers 2

2

This would give you the desired result in a single line:

s = " - ".join(s.split(' - ')[:-1])
Sign up to request clarification or add additional context in comments.

Comments

2

you want to use split for this!

In [130]: s = 'some Strings-and-stuff - SomeOther Strings-and-stuff - TAke.THis last -part away.txt'

In [131]: s.split(" - ")[0:-1]
Out[131]: ['some Strings-and-stuff', 'SomeOther Strings-and-stuff']

when you split by " - " it will return a list that has items that would have been separated in the string by " - ".

Then you index from the first item until the last item, which is why there is [0:-1] after the split

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.