4

I have a string with two "-"

467.2-123-hdxdlfow

I want to remove everything after the second "-" so that I get "467.2-123". What is the best way to do this?

7 Answers 7

13
before, sep, after = theString.rpartition("-")

This splits the str about the last occurrence of "-" and your answer would be the variable before.

10
In [6]: "-".join('467.2-123-hdxdlfow'.split('-')[0:2])
Out[6]: '467.2-123'
2
 >>> s = '467.2-123-hdxdlfow'
 >>> s[:s.rfind('-')]
 '467.2-123'
1
  • I like this one best because it works for any number of dashes - it will get rid of the last one and anything after it :)
    – karnok
    Oct 5, 2011 at 12:03
2

If you are after everything but the last element, I have modifed spicavigo's answer to exclude the last element.

a='467.2-123-hdxdlfow'
'-'.join(a.split('-')[:-1])
1
a='467.2-123-hdxdlfow'
'-'.join(a.split('-')[:2])

If you have exactly 2 '-', you could do

a.rsplit('-',1)[0]
0

Try this regex

([^-]*-[^-]*)-.*

and ask the result for the first capturing group ((...) in the example).

0

You can try this result = re.sub("([^-]*-[^-]*)(-.*$)", r"\1", '467.2-123-hdxdlfow') gives 467.2-123

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.