How to extract numbers from a string in Python?

后端 未结 17 2090
星月不相逢
星月不相逢 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:59

    I'd use a regexp :

    >>> import re
    >>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
    ['42', '32', '30']
    

    This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b :

    >>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
    ['42', '32', '30']
    

    To end up with a list of numbers instead of a list of strings:

    >>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
    [42, 32, 30]
    

提交回复
热议问题