首页 > 解决方案 > Python3 isnumeric() 方法未按预期工作

问题描述

我只是开始探索其他一些 Python 方法,例如 isnumeric()。我有一个分配任务,我要从文本中搜索和提取数字。我已经发布了下面的代码。

handle = open("words3.txt")
for line in handle:
   line = line.rstrip()
   split = line.split()
   for word in split:
      x = word.isnumeric()
      print(x)

有了这个,我得到了回溯......但我认为我已经遵循了 str.isnumeric() 的规则。有人可以告诉我我做错了什么吗?

File "assignment11.py", line 10, in <module>
    x = word.isnumeric()
AttributeError: 'str' object has no attribute 'isnumeric'

标签: pythonpython-3.x

解决方案


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

s = u'This is my string'
#OR
s=unicode('some string', 'utf-8')
isnum = s.isnumeric()

或者您可以这样做以更改wordstring

x = str(word).isnumeric()

推荐阅读