简体   繁体   English

python:在一个字符后分割字符串

[英]python: split string after a character

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". 我希望在第二个“ - ”之后删除所有内容,以便我得到“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. 如果你追求的是最后一个元素,我已经修改了spicavigo的答案来排除最后一个元素。

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 如果你有2' - ',你可以做到

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM