如何在计算值时返回false

2024-06-11 08:06:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在将字符串转换为整数时,我希望返回没有任何错误的值。你知道吗

例如,如果我有一个字符串“Hello World”,当我想使用casting process时,它将返回false而不是error。你知道吗

这是我试图将字符串转换为int时的错误语句:

"ValueError: invalid literal for int() with base 10: 'From fairest creatures we desire increase,'"

string = int('我们渴望从最美丽的生物身上获得更多')


Tags: 字符串falsehelloforworld错误整数error
3条回答

严格按照您的要求,但请进一步阅读:

def to_int(string):
    try:
        return int(string)
    except ValueError:
        return False

但在我看来,它应该返回None,而不是False。为什么?布尔可以视为整数[sic]:

>>> True + True
2
>>> False + False
2
>>> True < 2
True
>>> False < 2
True
>>> True + 1
2
>>> False + 1
1

等等

所以我建议使用:

def to_int(string):
    try:
        return int(string)
    except ValueError:
        return None

它将帮助您避免一些奇怪的错误,更不用说它只是听起来更好。你知道吗

返回False当有一个免费的案例时True也可以返回。如果不是,则返回有效值或None(如果不可能)。你知道吗

你可以为它写一个函数。你知道吗

def to_int(string):
    try:
        return int(string)
    except ValueError:
        return False

并这样称呼它:

>>> to_int("Hello World")
False
>>> to_int("10")
10

如果希望更灵活,还可以添加可选的默认值

def to_int(string, default = False):
    try:
        return int(string)
    except ValueError:
        return default
def fun(str):
    if str.isdigit():
        return int(str)
    else:
        return False

如果整个字符串是数字,此函数将返回int值,否则将返回False

相关问题 更多 >