如果字符串是 '007w',那么当它尝试将 '007w' 作为整数返回时,我希望它return None和print('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)