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.

Sign up to request clarification or add additional context in comments.

Comments

10
In [6]: "-".join('467.2-123-hdxdlfow'.split('-')[0:2])
Out[6]: '467.2-123'

Comments

2
 >>> s = '467.2-123-hdxdlfow'
 >>> s[:s.rfind('-')]
 '467.2-123'

1 Comment

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 :)
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])

Comments

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

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

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

Comments

0

Try this regex

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

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

Comments

0

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

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.