How to extract numbers from a string in Python?

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

    If you only want to extract only positive integers, try the following:

    >>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
    >>> [int(s) for s in str.split() if s.isdigit()]
    [23, 11, 2]
    

    I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.

    This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.

提交回复
热议问题