Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string has a numeric value in it in Python? [duplicate]

Possible Duplicate:
How do I check if a string is a number in Python?
Python - Parse String to Float or Int

For example, I want to check a string and if it is not convertible to integer(with int()), how can I detect that?

like image 718
Figen Güngör Avatar asked Sep 17 '12 19:09

Figen Güngör


People also ask

How do you check if a string is a numeric value in Python?

Python String isnumeric() MethodThe isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do you check if a string is alphanumeric in Python?

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). Example of characters that are not alphanumeric: (space)!

How do you check if a string is a decimal Python?

Python String isdecimal() The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.


2 Answers

Use the .isdigit() method:

>>> '123'.isdigit() True >>> '1a23'.isdigit() False 

Quoting the documentation:

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For unicode strings or Python 3 strings, you'll need to use a more precise definition and use the unicode.isdecimal() / str.isdecimal() instead; not all Unicode digits are interpretable as decimal numbers. U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example.

like image 157
Martijn Pieters Avatar answered Sep 20 '22 21:09

Martijn Pieters


You can always try it:

try:    a = int(yourstring) except ValueError:    print "can't convert" 

Note that this method outshines isdigit if you want to know if you can convert a string to a floating point number using float

like image 29
mgilson Avatar answered Sep 22 '22 21:09

mgilson