字符串到 int ValueError Python

drl*_*chy 0 python types valueerror

如果字符串是 '007w',那么当它尝试将 '007w' 作为整数返回时,我希望它return Noneprint('Cannot be converted). 但不使用 Try 除外 ValueError:

import random

def random_converter(x):
    selection = random.randint(1,5)
    if selection == 1:
        return int(x)
    elif selection == 2:
        return float(x)
    elif selection == 3:
        return bool(x)
    elif selection == 4:
        return str(x)
    else:
        return complex(x)


for _ in range(50):
    output = random_converter('007w')
    print(output, type(output))
Run Code Online (Sandbox Code Playgroud)

Nic*_*eed 5

您可以使用str.isdigit()来检查python中的字符串是否可以解析为数字。如果所有值都是数字,则返回 true,否则返回 false。

请注意,isdigit()它的能力相当有限 - 它无法处理小数点或负数。如果您希望解析比正整数更复杂的任何内容,您可能需要考虑try/except


def parse(in_str):
  if(in_str.isdigit()):
    return int(in_str)
  else:
    print('Cannot be converted')
    return(None)

print(parse("1234"))
print(parse("007w"))
Run Code Online (Sandbox Code Playgroud)

1234
无法转换

演示