Splitting a string where it switches between numeric and alphabetic characters

前端 未结 4 1191
闹比i
闹比i 2020-12-30 02:20

I am parsing some data where the standard format is something like 10 pizzas. Sometimes, data is input correctly and we might end up with 5pizzas i

4条回答
  •  悲哀的现实
    2020-12-30 02:56

    Answer added as possible way to solve How to split a string into a list by digits? which was dupe-linked to this question.

    You can do the splitting yourself:

    • use a temporary list to accumulate characters that are not digits
    • if you find a digit, add the temporary list (''.join()-ed) to the result list (only if not empty) and do not forget to clear the temporary list
    • repeat until all characters are processed and if the temp-lists still has content, add it

    text = "Ka12Tu12La"
    
    splitted = []   # our result
    tmp = []        # our temporary character collector
    
    for c in text:
        if not c.isdigit():
            tmp.append(c)    # not a digit, add it
    
        elif tmp:            # c is a digit, if tmp filled, add it  
            splitted.append(''.join(tmp))
            tmp = []
    
    if tmp:
        splitted.append(''.join(tmp))
    
    print(splitted)
    

    Output:

    ['Ka', 'Tu', 'La']
    

    References:

    • What exactly does the .join() method do?

提交回复
热议问题