I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Traceback (most recent call last)
<ipython-input-4-859c9cefa0f0> in <module>()
3
4 # test to see if it is numeric
----> 5 string_isnumeric = string.isnumeric()
AttributeError: 'str' object has no attribute 'isnumeric'
The problem is that, as far as I can tell, str
DOES have an attribute, isnumeric
.
The 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 . are not.
Python String isnumeric() Method The str. isnumeric() checks whether all the characters of the string are numeric characters or not. It will return True if all characters are numeric and will return False even if one character is non-numeric.
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.
No, str
objects do not have an isnumeric
method. isnumeric
is only available for unicode objects. In other words:
>>> d = unicode('some string', 'utf-8') >>> d.isnumeric() False >>> d = unicode('42', 'utf-8') >>> d.isnumeric() True
isnumeric()
only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:
In [4]: s = u'This is my string' isnum = s.isnumeric()
This will now store False.
Note: I also changed your variable name in case you imported the module string.
One Liners:
unicode('200', 'utf-8').isnumeric() # True
unicode('unicorn121', 'utf-8').isnumeric() # False
Or
unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With