Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

python - 如何检查字符串是否为数字(浮点数)?(How do I check if a string is a number (float)?)

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

(检查字符串是否可以在Python中表示为数字的最佳方法是什么?)

The function I currently have right now is:

(我目前拥有的功能是:)

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Which, not only is ugly and slow, seems clunky.

(不仅丑陋且缓慢,而且看起来笨拙。)

However I haven't found a better method because calling float in the main function is even worse.

(但是我还没有找到更好的方法,因为在main函数中调用float更加糟糕。)

  ask by Daniel Goldberg translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

(如果您正在寻找解析(正,无符号)整数而不是浮点数,则可以将isdigit()函数用于字符串对象。)

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

String Methods - isdigit() : Python2 , Python3

(字符串方法-isdigit isdigit()Python2Python3)

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

(Unicode字符串上也有一些内容,我不太熟悉Unicode-是十进制/十进制)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...