How to extract integers from a string separated by spaces in Python 2.7?

后端 未结 4 2124
南笙
南笙 2021-01-05 16:25

I want to extract integers from a string in which integers are separated by blank spaces i.e \' \'. How could I do that ??

Input

I=\'1 15 163 132\'
<         


        
4条回答
  •  梦毁少年i
    2021-01-05 16:47

    You could simply do like this,

    >>> import re
    >>> I='bar 1 15 foo 163 132 foo bar'
    >>> [int(i) for i in I.split() if re.match(r'^\d+$', i)]
    [1, 15, 163, 132]
    

    Without regex:

    >>> I='bar 1 15 foo 163 132 foo bar'
    >>> [int(i) for i in I.split() if i.isdigit()]
    [1, 15, 163, 132]
    

    i.isdigit() returns true only for the strings which contain only digits.

提交回复
热议问题