小编drl*_*chy的帖子

字符串到 int ValueError Python

如果字符串是 '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)

python types valueerror

0
推荐指数
1
解决办法
144
查看次数

标签 统计

python ×1

types ×1

valueerror ×1