How to extract numbers from a string in Python?

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

    @jmnas, I liked your answer, but it didn't find floats. I'm working on a script to parse code going to a CNC mill and needed to find both X and Y dimensions that can be integers or floats, so I adapted your code to the following. This finds int, float with positive and negative vals. Still doesn't find hex formatted values but you could add "x" and "A" through "F" to the num_char tuple and I think it would parse things like '0x23AC'.

    s = 'hello X42 I\'m a Y-32.35 string Z30'
    xy = ("X", "Y")
    num_char = (".", "+", "-")
    
    l = []
    
    tokens = s.split()
    for token in tokens:
    
        if token.startswith(xy):
            num = ""
            for char in token:
                # print(char)
                if char.isdigit() or (char in num_char):
                    num = num + char
    
            try:
                l.append(float(num))
            except ValueError:
                pass
    
    print(l)
    

提交回复
热议问题