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?
before, sep, after = theString.rpartition("-")
这会将str分成最后一次出现的“ - ”,你的答案就是before
的变量。
In [6]: "-".join('467.2-123-hdxdlfow'.split('-')[0:2])
Out[6]: '467.2-123'
>>> s = '467.2-123-hdxdlfow'
>>> s[:s.rfind('-')]
'467.2-123'
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])
a='467.2-123-hdxdlfow'
'-'.join(a.split('-')[:2])
If you have exactly 2 '-', you could do
a.rsplit('-',1)[0]
Try this regex
([^-]*-[^-]*)-.*
and ask the result for the first capturing group ( (...)
in the example).
你可以尝试这个result = re.sub("([^-]*-[^-]*)(-.*$)", r"\\1", '467.2-123-hdxdlfow')
给出467.2-123
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.