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.

26th Mar 2019, 7:13 AM
Daniel. S (שריד)
Daniel. S (שריד) - avatar
6 Réponses
+ 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.
26th Mar 2019, 7:22 AM
Letsintegreat
Letsintegreat - avatar
+ 7
Daniel. S (שריד) added in my main answer
26th Mar 2019, 8:13 AM
Letsintegreat
Letsintegreat - avatar
+ 6
Daniel. S (שריד) Pleased to help you😊
26th Mar 2019, 8:09 AM
Letsintegreat
Letsintegreat - avatar
+ 1
Zlytherin Thanks, it’s worked!
26th Mar 2019, 8:08 AM
Daniel. S (שריד)
Daniel. S (שריד) - avatar
+ 1
btw: What’s the different between .isdigit and .isnumeric?
26th Mar 2019, 8:09 AM
Daniel. S (שריד)
Daniel. S (שריד) - avatar
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.
26th Mar 2019, 8:02 AM
Daniel. S (שריד)
Daniel. S (שריד) - avatar