将 isdigit 用于浮点数? [英] Using isdigit for floats?

查看:36
本文介绍了将 isdigit 用于浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = raw_input('How much is 1 share in that company? ')

while not a.isdigit():
    print("You need to write a number!
")
    a = raw_input('How much is 1 share in that company? ')

这仅在用户输入 integer 时有效,但我希望即使他们输入 float 也能起作用,但在输入 string 时不起作用.

This only works if the user enters an integer, but I want it to work even if they enter a float, but not when they enter a string.

所以用户应该能够同时输入99.2,但不能输入abc.

So the user should be able to enter both 9 and 9.2, but not abc.

我该怎么做?

推荐答案

使用正则表达式.

import re

p = re.compile('d+(.d+)?')

a = raw_input('How much is 1 share in that company? ')

while p.match(a) == None:
    print "You need to write a number!
"
    a = raw_input('How much is 1 share in that company? ')

这篇关于将 isdigit 用于浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆