可以使用.isdigit()方法来判断字符串是否为非负数。

def is_non_negative(string):
    return string.isdigit()

print(is_non_negative("123"))  # True
print(is_non_negative("-123"))  # False
print(is_non_negative("0"))  # True
print(is_non_negative("12.3"))  # False

注意,这种方法只能判断整数部分是否为非负数,如果字符串包含小数点或者负号,该方法会返回False。如果需要判断包含小数的非负数,可以使用正则表达式匹配。

import re

def is_non_negative(string):
    return re.match(r"^\d+(\.\d+)?$", string) is not None

print(is_non_negative("123"))  # True
print(is_non_negative("-123"))  # False
print(is_non_negative("0"))  # True
print(is_non_negative("12.3"))  # True
``
python 判断字符串是非负数

原文地址: https://www.cveoy.top/t/topic/ieHQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录