How to extract numbers from a string in Python?

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

    Using Regex below is the way

    lines = "hello 12 hi 89"
    import re
    output = []
    #repl_str = re.compile('\d+.?\d*')
    repl_str = re.compile('^\d+$')
    #t = r'\d+.?\d*'
    line = lines.split()
    for word in line:
            match = re.search(repl_str, word)
            if match:
                output.append(float(match.group()))
    print (output)
    

    with findall re.findall(r'\d+', "hello 12 hi 89")

    ['12', '89']
    

    re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")

    ['12', '89', '777']
    

提交回复
热议问题