【问题标题】:Why isn't isnumeric working?为什么数字不起作用?
【发布时间】:2019-10-22 14:06:57
【问题描述】:

我正在通过一个非常简单的 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'

问题在于,据我所知,str DOES 有一个属性 isnumeric

【问题讨论】:

  • 不在 Python 2 中,将该字符串更改为 unicode 字符串。
  • 尝试改用isdigit
  • 找到答案:文本在Py3中默认为unicode。 stackoverflow.com/questions/16863696/…
  • 将其发布为带有解释的答案。接受。问题已解决。

标签: python python-3.x


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    In [4]:
            s = u'This is my string'
    
            isnum = s.isnumeric()
    

    这将存储 False。

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

    【讨论】:

      【解决方案3】:

      一个衬里:

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

      或者

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

      【讨论】:

        【解决方案4】:

        如果使用 python 3 将字符串包裹在 str 周围,如下所示

        str('hello').isnumeric()

        这样它的行为符合预期

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多