gpt4 book ai didi

python - 你如何在python中检查一个字符串是否只包含数字?

转载 作者:IT老高 更新时间:2023-10-28 21:08:20 25 4
gpt4 key购买 nike

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

我已经尝试过了。我想看看实现这一点的最简单方法。

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 方法:

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

来自 isdigit documentation :

str.isdigit()

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 - 你如何在python中检查一个字符串是否只包含数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21388541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com