[英]how to split string after certain character in python
如果我有一个字符串,就说吧, ba hello b Hi
,我怎么能在字母a
第一次出现后用全b
分割字符串?
与之一样,它将返回["ba hello", "Hi"]
。
在此处记录: str.rsplit()
sentence = 'b a hello b Hi'
sentence.rsplit('b', 1)
如果您注意到门的位置(第一个“ a”),则可以在该点之后分割字符串,例如:
a_string = 'b a hello b Hi'
first_a = a_string.index('a')
a_split = a_string[first_a:].split('b')
a_split[0] = a_string[:first_a] + a_split[0]
a_split = [x.strip() for x in a_split]
print(a_split)
['b a hello', 'Hi']
str = 'b a hello b Hi'
print(str[str.index('a'):].split('b'))
str = "b a hello b Hi"
res = str[str.find("a"):].split("b")
res[0] = str[:str.find("a")] + res[0]
print res
# ['b a hello ', ' Hi']
尝试这个:-
a = "b a hello b Hi"
x = [x for x,y in enumerate(a) if y=='b']
ls = [a[x[0]:x[-1]],a[x[-1]+1:].strip()]
print(ls)
使用以下代码
s = 'b a hello b Hi'
i = s.index("a")
s2 = s[i+1:].strip()
l = s2.split(" b ")
print(l)
在示例结果中,您将字符串用'b'分隔,因此我将使用它。
a = "b a hello b Hi"
index = a.index('a') + a[a.index('a'):].index(' b ') # That's the index of first ' b '.
# Since split will give 1 empty element at the beginning I exclude that.
result = [a[:index]] + a[index:].split(' b ')[1:]
# ['b a hello', 'Hi']
如果要用“ b”分隔,请替换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.