laszlopanaflex
laszlopanaflex

Reputation: 1916

splitting a string in python based on first occurrence of letter

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

Upvotes: 0

Views: 217

Answers (2)

dawg
dawg

Reputation: 103874

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

Upvotes: 0

oreopot
oreopot

Reputation: 3450

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

Upvotes: 2

Related Questions