How to extract numbers from a string in Python?

后端 未结 17 2042
星月不相逢
星月不相逢 2020-11-21 05:19

I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the isdigit() method?

Example:

17条回答
  •  臣服心动
    2020-11-21 05:55

    I am amazed to see that no one has yet mentioned the usage of itertools.groupby as an alternative to achieve this.

    You may use itertools.groupby() along with str.isdigit() in order to extract numbers from string as:

    from itertools import groupby
    my_str = "hello 12 hi 89"
    
    l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]
    

    The value hold by l will be:

    [12, 89]
    

    PS: This is just for illustration purpose to show that as an alternative we could also use groupby to achieve this. But this is not a recommended solution. If you want to achieve this, you should be using accepted answer of fmark based on using list comprehension with str.isdigit as filter.

提交回复
热议问题