How to extract numbers from a string in Python?

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

    To catch different patterns it is helpful to query with different patterns.

    Setup all the patterns that catch different number patterns of interest:

    (finds commas) 12,300 or 12,300.00

    '[\d]+[.,\d]+'

    (finds floats) 0.123 or .123

    '[\d]*[.][\d]+'

    (finds integers) 123

    '[\d]+'

    Combine with pipe ( | ) into one pattern with multiple or conditionals.

    (Note: Put complex patterns first else simple patterns will return chunks of the complex catch instead of the complex catch returning the full catch).

    p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
    

    Below, we'll confirm a pattern is present with re.search(), then return an iterable list of catches. Finally, we'll print each catch using bracket notation to subselect the match object return value from the match object.

    s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
    
    if re.search(p, s) is not None:
        for catch in re.finditer(p, s):
            print(catch[0]) # catch is a match object
    

    Returns:

    33
    42
    32
    30
    444.4
    12,001
    

提交回复
热议问题