Python - ValueError:基数为10的int()的无效文字:'xyz'

时间:2017-04-11 13:20:04

标签: python

我有以下代码段:

for image_name in images:
    img_id = int(image_name.split('.')[0])
    img = skimage.io.imread(os.path.join(train_data_path, image_name))
    img = np.array([img])

收到以下错误:

Traceback (most recent call last):
  File "data_original.py", line 99, in <module>
    create_test_data()
  File "data_original.py", line 74, in create_test_data
    img_id = int(image_name.split('.')[0])
ValueError: invalid literal for int() with base 10: 'ISIC_1000'

我尝试将int替换为float,但收到以下错误:

Traceback (most recent call last):
  File "data_original.py", line 97, in <module>
    create_test_data()
  File "data_original.py", line 72, in create_test_data
    img_id = float(image_name.split('.')[0])
ValueError: could not convert string to float: 'ISIC_1000'

如何解决上述问题?

感谢。

1 个答案:

答案 0 :(得分:0)

你必须确保传递给int()的参数可以转换为数字,假设:image_name.split('.')[0]返回包含字母(aZ)的sting或其他不是数字的字符(例如:& #39; xyz&#39;或&#39; ISIC_1000&#39;)。

您也可以使用try/except