Search code examples
pythonsplitpython-re

I'm using re.split() and trying to join the elements but it doesn't work. Why is it?


I have a problem and I can't find reason why. I want to divide the string into 3 parts, and the condition is "integer+Letter+*(optional)" it works well when the number is one digit, but it doesn't work when the number is two digits.

This is my code:

import re
dartResult = '10S*3T2D*'
dartresult = re.split('(\d)',dartResult)   
dartresult=[i for i in dartresult if i != ""]
score = []
for i in range(len(dartresult)):
    try:
        if int(dartresult[i]):
            score.append(["".join(dartresult[i:i+2])])
        elif int(dartresult[i]) and int(dartresult[i+1]):   #in case the number is two digits
            score.append(["".join(dartresult[i:i+3])])    
    except:
        pass
print(dartresult)
print(score)

and this is the result.

['1', '0', 'S*', '3', 'T', '2', 'D*']
[['10'], ['3T'], ['2D*']]

and it would be nice if you let me know if there's a better way to divide the strings according to the condition above.


Solution

  • Why don't you simply define all the elements in your regex?

    import re
    dartResult = '10S*3T2D*'
    out = re.findall(r'\d+\w\*?', dartResult)
    

    output:

    >>> out
    ['10S*', '3T', '2D*']
    

    regex:

    \d+     # one or more digits
    \w      # one character (letters/digit/underscore), to restrict to letters use [a-zA-Z]
    \*?     # optionally, one "*" character