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

编程入门 行业动态 更新时间:2024-10-17 17:16:17
你如何检查python一个字符串是否只包含数字?(How do you check in python whether a string contains only numbers?)

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

我已经去了这里。 我想看到最简单的方式来完成这个。

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

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

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

从isdigit文档:

str.isdigit()

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

对于8位字符串,此方法与区域设置相关。

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

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

From the isdigit documentation:

str.isdigit()

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

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

更多推荐

本文发布于:2023-04-28 01:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字   python   numbers   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!