0

as an example, I have the string '10d45x'

I would like to take the string as an input and retrieve '10d' and '45x' separately.

some clarifications: the letters can always be of 1 character length but the numbers can be longer

I am trying to explore:

import re
re.split("[a-zA-Z]",'10d45x')

but unable to find the right parameters to get exactly what I want

laszlopanaflex
  • 1,836
  • 3
  • 23
  • 34
  • What have you tried so far? – oreopot May 23 '20 at 02:09
  • It's not really clear what other patterns you might encounter. Do all the groups you want fit the pattern of some-numbers-and-a-letter? If so, it's just `re.findall(r'\d+\w', s)` – Mark May 23 '20 at 02:10

2 Answers2

2

Try the following code:

option 1: (credits to Mark Meyer )

import re
str = '10d45x'
print(re.findall(r'\d+\w', str))

option: 2

str = '10d45x'
final_list = []
temp_list = []
for i in str:
    temp_list.append(i)
    if (i.isalpha()):
        final_list.append("".join(temp_list))
        temp_list = []
print(final_list)
>>> ['10d', '45x']
oreopot
  • 3,392
  • 2
  • 19
  • 28
0

You can split directly looking back for a letter and forward for a digit:

>>> re.split(r'(?<=[a-zA-Z])(?=\d)', '10d45x')
['10d', '45x']

Instead of splitting you can also capture:

>>> re.findall(r'(\d+[a-zA=Z])', '10d45x')
['10d', '45x']
dawg
  • 98,345
  • 23
  • 131
  • 206