如何在Python中按照特定字符分割字符串

9
如果我有一个字符串,比如说,b a hello b Hi,如何将该字符串按所有第一个字母为ab分割成多个部分? 例如,它将返回["b a hello", "Hi"]

这个回答解决了你的问题吗?如何获取特定子字符串后面的字符串? - JayRizzo
7个回答

10
这里有文档说明:str.rsplit()
sentence = 'b a hello b Hi'
sentence.rsplit('b', 1)

这并没有回答帖子关于字母a出现的问题;它需要硬编码值“1”,对应于知道它是在第一个出现的b之后的第二个出现的a。 - K. Nielson

3
如果您注意到门(第一个'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']

1
尝试这个:-
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)

0
str = 'b a hello b Hi'
print(str[str.index('a'):].split('b'))

0
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']

0
请使用以下代码。
s = 'b a hello b Hi'
i = s.index("a")
s2 = s[i+1:].strip()
l = s2.split(" b ")
print(l)

0
在你的示例结果中,你使用 ' 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'分割,则替换它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接