Python: how do I use isnumeric()
本问题已经有最佳答案,请猛点这里访问。
有人能解释一下为什么下面会抛出异常吗?我应该如何处理变量
1 2 3  | s = str(10) if s.isnumeric(): print s  | 
当我阅读python文档时,上面的内容对我来说应该是有效的。见:
https://docs.python.org/3/library/stdtypes.html?highlight=isNumeric str.isNumeric
但我得到的是:
"AttributeError: 'str' object has no attribute 'isnumeric'"
任何帮助都是最感激的。
谢谢您!
尝试将
1  | print(s.replace('.', '').isdigit())  | 
对于python 2 isdigit(),对于python 3 isnumeric()。
python 2
1 2 3  | s = str(10) if s.isdigit(): print s  | 
python 3
1 2 3  |  s = str(10) if s.isnumeric(): print(s)  | 
用
1 2 3  | s = str(10) if s.isdigit(): print s  | 
显然您使用的是python 2,因此不存在这样的方法。
这就是说,最要紧的办法就是把它转换成
1 2 3 4  | try: print(float(s)) # or int(s) except ValueError: print("s must be numeric")  |