9

If I have a string, lets just say, b a hello b Hi, how could I split the string by all bs AFTER the first occurrence of the letter a?

As in, it would return ["b a hello", "Hi"].

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Person
  • 379
  • 1
  • 3
  • 15
  • Does this answer your question? [How to get a string after a specific substring?](https://stackoverflow.com/questions/12572362/how-to-get-a-string-after-a-specific-substring) – JayRizzo May 20 '22 at 07:33

7 Answers7

10

This is documented here: str.rsplit()

sentence = 'b a hello b Hi'
sentence.rsplit('b', 1)
  • This doesn't address the poster's question with respect to the occurrence of the letter a; it requires a hardcoded value of `1` corresponding to knowledge that it is the second occurrence of `b` that follows the first occurrence of `a`. – K. Nielson Dec 20 '22 at 16:16
3

If you note the location of the gate (first 'a') then you can split the string after that point like:

Code:

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)

Result:

['b a hello', 'Hi']
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

Try this:-

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)
Narendra
  • 1,511
  • 1
  • 10
  • 20
0
str = 'b a hello b Hi'
print(str[str.index('a'):].split('b'))
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
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']
陈敏华
  • 1,365
  • 1
  • 9
  • 9
0

Use the following code

s = 'b a hello b Hi'
i = s.index("a")
s2 = s[i+1:].strip()
l = s2.split(" b ")
print(l)
0

In your example result you split the string by ' b ' so I'm going to use that.

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

If you want to split by 'b' then replace them.