Python:如何使用isnumeric()

时间:2019-03-07 09:25:57

标签: python

有人可以请您解释以下内容引发异常的原因吗?我该如何使用变量s来找出变量是否包含数字?

s = str(10)
if s.isnumeric():
    print s

当我阅读Python文档时,以上内容应该可以正常工作。参见:

https://docs.python.org/3/library/stdtypes.html?highlight=isnumeric#str.isnumeric

但是我得到的是:

  

“ AttributeError:'str'对象没有属性'isnumeric'”

我们非常感谢您的帮助。

谢谢!

4 个答案:

答案 0 :(得分:1)

isnumeric()替换为isdigit()

s = str(10)
if s.isdigit():
    print s

答案 1 :(得分:1)

对于python 2 isdigit()和python 3 isnumeric()

  

python 2

s = str(10)
if s.isdigit():
    print s
  

python 3

 s = str(10)
 if s.isnumeric():
    print(s)

答案 2 :(得分:1)

尝试将android/app/src/debug/res/xml/react_native_config.xml<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="false">localhost</domain> <domain includeSubdomains="false">10.0.2.2</domain> <domain includeSubdomains="false">10.0.3.2</domain> <domain includeSubdomains="true">dev.local</domain> </domain-config> </network-security-config> 一起使用:

replace

答案 3 :(得分:0)

您显然正在使用python 2,因此不存在这样的方法。

也就是说,最pythonic的方法是尝试将其转换

try:
    print(float(s))  # or int(s)
except ValueError:
    print("s must be numeric")