How to split a string (using regex?) depending on digit/ not digit

前端 未结 4 849
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 12:54

I want to split a string into a list in python, depending on digit/ not digit. For example,

5 55+6+  5/

should return

[\'5\',\'         


        
相关标签:
4条回答
  • 2021-01-28 13:40

    Assuming the + between 6 and 5 needs to be matched (which you're missing),

    >>> import re
    >>> s = '5 55+6+ 5/'
    >>> re.findall(r'\d+|[^\d\s]+', s)
    ['5', '55', '+', '6', '+', '5', '/']
    
    0 讨论(0)
  • 2021-01-28 13:42

    Use findall or finditer:

    >>> re.findall(r'\d+|[^\s\d]+', '5 55+6+ 5/')
    ['5', '55', '+', '6', '+', '5', '/']
    
    0 讨论(0)
  • 2021-01-28 13:43

    this one is simplest one :)

    re.findall('\d+|[^\d]+','134aaaaa')
    
    0 讨论(0)
  • 2021-01-28 13:57

    If order doesn't matter, you could do 2 splits:

    re.split('\D+', mystring)
    
    re.split('\d+', mystring)
    

    However, from your input, it looks like it might be mathematical... in which case order would matter. :)

    You are best off using re.findall, as in one of the other answers.

    0 讨论(0)
提交回复
热议问题