How do you check whether a string contains only numbers?

如何检查字符串是否只包含数字?

I've given it a go here. I'd like to see the simplest way to accomplish this.

我已经在这里试了一下。我想看看实现这一目标的最简单方法。

import string

def main():
    isbn = input("Enter your 10 digit ISBN number: ")
    if len(isbn) == 10 and string.digits == True:
        print ("Works")
    else:
        print("Error, 10 digit number was not inputted and/or letters were inputted.")
        main()

if __name__ == "__main__":
    main()
    input("Press enter to exit: ")

6 个解决方案

#1


145

You'll want to use the isdigit method on your str object:

您将要在str对象上使用isdigit方法:

if len(isbn) == 10 and isbn.isdigit():

From the isdigit documentation:

从isdigit文档:

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

如果字符串中的所有字符都是数字且至少有一个字符,则返回true,否则返回false。

For 8-bit strings, this method is locale-dependent.

对于8位字符串,此方法取决于区域设置。

更多相关文章

  1. 在java中调用python方法
  2. Python中字典合并的实现方法
  3. Python 学习笔记【list的操作方法】
  4. 使用pip安装tensorflow 0.80,python 使用tensorflow 0.80遇到的问
  5. Python - 去除字符串首尾填充
  6. Python处理字符串
  7. python list range 字符串的截取 如 text[1:5]
  8. 在save方法中创建两个对象
  9. 基于Python的XSS测试工具XSStrike使用方法

随机推荐

  1. 平分的直线 牛客网 程序员面试金典 C++ P
  2. python排序列表与铸造
  3. python实现微信自动聊天
  4. Ubuntu 下TinyOS在CC2530上移植之环境搭
  5. 055 Python第三方库安装
  6. Process Pool实现Python的并行执行
  7. Python学习笔记(3):数据集操作-列的统一操作
  8. Linux中Python安装与配置(CentOS-6.5:Pyth
  9. Python列表和字典的学习
  10. Python Django Vue 项目创建