How to extract numbers from a string in Python?

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

    If you know it will be only one number in the string, i.e 'hello 12 hi', you can try filter.

    For example:

    In [1]: int(''.join(filter(str.isdigit, '200 grams')))
    Out[1]: 200
    In [2]: int(''.join(filter(str.isdigit, 'Counters: 55')))
    Out[2]: 55
    In [3]: int(''.join(filter(str.isdigit, 'more than 23 times')))
    Out[3]: 23
    

    But be carefull !!! :

    In [4]: int(''.join(filter(str.isdigit, '200 grams 5')))
    Out[4]: 2005
    

提交回复
热议问题