0
How to detect that a String contains only numbers?
I have a String that equal to an input from the User, and I want the program will make sure that the User types only numbers/Decimal numbers/negative numbers for converting the String to a Float(or Int) later. I tried using the methods .isnumeric() / .isdigit() but its wuoldn't recognize decimal and negative numbers. (Btw what's the different between these two methods?) Any suggestion how to check it? Thanks.
6 Answers
+ 11
You can add the conversion in try / catch statement
Like this:
try:
num = int(a)
except ValueError:
print("Invalid")
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
str.isdigit
Return true if all characters in the string are digits and there is at least one character, false otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
str.isnumeric
Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
+ 7
Daniel. S (׊ר××) added in my main answer
+ 6
Daniel. S (׊ר××) Pleased to help youđ
+ 1
Zlytherin Thanks, itâs worked!
+ 1
btw: Whatâs the different between .isdigit and .isnumeric?
0
Jay Matthews Sorry Iâm not sure I understand what you mean. Of cource c is not equal to â.â in any case. because if for example: c = 3.2 it would not equal to â.â because it has more charecters in it (3, 2)
so it will allways continue to the next line and then I will get the same problem.