你如何在python中检查一个字符串是否只包含数字? [英] How do you check in python whether a string contains only numbers?

查看:80
本文介绍了你如何在python中检查一个字符串是否只包含数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何判断一个字符串是否只包含数字?

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: ")

推荐答案

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

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

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

来自 isdigit 文档:

From the isdigit documentation:

str.isdigit()

如果字符串中的所有字符都是数字并且至少有一个字符,则返回 True,否则返回 False.数字包括十进制字符和需要特殊处理的数字,例如兼容性上标数字.这涵盖了不能用于​​形成以 10 为基数的数字的数字,例如 Kharosthi 数字.形式上,数字是具有属性值 Numeric_Type=Digit 或 Numeric_Type=Decimal 的字符.

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

这篇关于你如何在python中检查一个字符串是否只包含数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆