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

后端 未结 30 3929
暗喜
暗喜 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:44

    Here's my simple way of doing it. Let's say that I'm looping through some strings and I want to add them to an array if they turn out to be numbers.

    try:
        myvar.append( float(string_to_check) )
    except:
        continue
    

    Replace the myvar.apppend with whatever operation you want to do with the string if it turns out to be a number. The idea is to try to use a float() operation and use the returned error to determine whether or not the string is a number.

提交回复
热议问题