数据类型转换失败:Python中的类型转换问题示例
在Python中,如果尝试将一个不兼容的数据类型转换为另一种类型,会出现TypeError。下面是一些示例:
- 整数到浮点数:
int_value = 5
float_value = int_value + .01 # 尝试添加一个小数部分
print(float_value) # 输出: 5.01
- 字符串到整数:
str_value = "123"
try:
int_value = int(str_value) # 尝试将字符串转换为整数
except ValueError as e:
print(f"Error: {e}, Unable to convert string to integer") # 输出:错误: invalid literal for int() with base 10, 不能将字符串转换为整数
- 列表到字典:
以上示例展示了如何在Python中进行类型转换,如果转换失败会抛出TypeError。list_value = [('Name', 'John'), ('Age', 25)]
try:
dict_value = dict(list_value[0]) # 尝试将列表中的元素转化为字典
except TypeError as e:
print(f"Error: {e}, Unable to convert list to dictionary") # 输出:错误: unhashable type: 'list', 不能将列表转换为字典
还没有评论,来说两句吧...