dawed1999
dawed1999

Reputation: 335

splitting a string by specific letters while preserving them in the string

I'm trying to split a string by specific letters(in this case:'r','g' and'b') so that I can then later append them to a list. The catch here is that I want the letters to be copied to over to the list as well.

string = '1b24g55r44r'

What I want:

[[1b], [24g], [55r], [44r]]

Upvotes: 1

Views: 62

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61930

You can use findall:

import re

print([match for match in re.findall('[^rgb]+?[rgb]', '1b24g55r44r')])

Output

['1b', '24g', '55r', '44r']

The regex match:

  • [^rgb]+? everything that is not rgb one or more times
  • followed by one of [rgb].

If you need the result to be singleton lists you can do it like this:

print([[match] for match in re.findall('[^rgb]+?[rgb]', '1b24g55r44r')])

Output

[['1b'], ['24g'], ['55r'], ['44r']]

Also if the string is only composed of digits and rgb you can do it like this:

import re

print([[match] for match in re.findall('\d+?[rgb]', '1b24g55r44r')])

The only change in the above regex is \d+?, that means match one or more digits.

Output

[['1b'], ['24g'], ['55r'], ['44r']]

Upvotes: 7

Related Questions