How do I check if a string is a number (float)?

后端 未结 30 3922
暗喜
暗喜 2020-11-21 05:16

What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_numb         


        
30条回答
  •  广开言路
    2020-11-21 05:54

    I was working on a problem that led me to this thread, namely how to convert a collection of data to strings and numbers in the most intuitive way. I realized after reading the original code that what I needed was different in two ways:

    1 - I wanted an integer result if the string represented an integer

    2 - I wanted a number or a string result to stick into a data structure

    so I adapted the original code to produce this derivative:

    def string_or_number(s):
        try:
            z = int(s)
            return z
        except ValueError:
            try:
                z = float(s)
                return z
            except ValueError:
                return s
    

提交回复
热议问题