python判断字符串为非负数
可以使用isdigit()函数来判断一个字符串是否为非负数。isdigit()函数返回一个布尔值,如果字符串只包含数字字符,则返回True,否则返回False。
以下是一个示例代码:
def is_non_negative_number(string):
if string.isdigit():
return True
else:
return False
# 测试示例
print(is_non_negative_number("12345")) # True
print(is_non_negative_number("-12345")) # False
print(is_non_negative_number("12.34")) # False
print(is_non_negative_number("abc")) # False
输出结果:
True
False
False
False
注意:这个方法只能用于判断整数型的非负数,如果要判断包含小数点的非负数,可以使用正则表达式进行匹配
原文地址: https://www.cveoy.top/t/topic/ieEO 著作权归作者所有。请勿转载和采集!