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

问题描述

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

while not a.isdigit():
    print("You need to write a number!\n")
    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!\n"
    a = raw_input('How much is 1 share in that company? ')

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

07-04 03:55