Python 为什么 isnumeric 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23183868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:25:58  来源:igfitidea点击:

Why isn't isnumeric working?

pythonpython-3.x

提问by Anton

I was going through a very simple python3 guide to using string operations and then I ran into this weird error:

我正在阅读一个非常简单的 python3 使用字符串操作的指南,然后我遇到了这个奇怪的错误:

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, strDOEShave an attribute, isnumeric.

问题是,据我所知,str确实有一个属性,isnumeric.

回答by theage

isnumeric()only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:

isnumeric()仅适用于 Unicode 字符串。要将字符串定义为 Unicode,您可以像这样更改字符串定义:

In [4]:
        s = u'This is my string'

        isnum = s.isnumeric()

This will now store False.

这现在将存储 False。

Note: I also changed your variable name in case you imported the module string.

注意:如果您导入了模块字符串,我还更改了您的变量名称。

回答by Alexander Ejbekov

No, strobjects do not have an isnumericmethod. isnumericis only available for unicode objects. In other words:

不,str对象没有isnumeric方法。isnumeric仅适用于 unicode 对象。换句话说:

>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True

回答by nvd

One Liners:

一个班轮:

unicode('200', 'utf-8').isnumeric() # True
unicode('unicorn121', 'utf-8').isnumeric() # False

Or

或者

unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False

回答by Swarit Agarwal

if using python 3 wrap string around stras shown below

如果使用 python 3 环绕str 的字符串,如下所示

str('hello').isnumeric()

str('你好').isnumeric()

This way it behaving as expected

这样它的行为符合预期