Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using isdigit for floats?

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? ') 

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.

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

How should I do it?

like image 663
Peter Nolan Avatar asked Nov 09 '10 20:11

Peter Nolan


People also ask

Does Isdigit work with floats?

The isdigit() function returns true if a string contains digits only and false if at least one character is not a digit. However, this function returns false if a string contains a float number even though a floating-point number is a valid string.

What is the difference between Isdigit and Isnumeric Python?

The Python isnumeric method has a number of key differences between the Python isdigit method. While the isidigit method checks whether the string contains only digits, the isnumeric method checks whether all the characters are numeric.

What does Isdigit check for?

The isdigit() method returns True if all characters in a string are digits or Unicode char of a digit. If not, it returns False.

Does Isdigit work for strings?

isdigit() only returns true for strings (here consisting of just one character each) contains only digits. Because only digits are passed through, int() always works, it is never called on a letter.


2 Answers

EAFP

try:     x = float(a) except ValueError:     print("You must enter a number") 
like image 58
dan04 Avatar answered Oct 05 '22 14:10

dan04


The existing answers are correct in that the more Pythonic way is usually to try...except (i.e. EAFP).

However, if you really want to do the validation, you could remove exactly 1 decimal point before using isdigit().

>>> "124".replace(".", "", 1).isdigit() True >>> "12.4".replace(".", "", 1).isdigit() True >>> "12..4".replace(".", "", 1).isdigit() False >>> "192.168.1.1".replace(".", "", 1).isdigit() False 

Notice that this does not treat floats any different from ints however. You could add that check if you really need it though.

like image 38
Cam Jackson Avatar answered Oct 05 '22 14:10

Cam Jackson