数据类型转换失败:Python中的类型转换问题示例

原创 谁借莪1个温暖的怀抱¢ 2025-03-03 06:42 30阅读 0赞

在Python中,如果尝试将一个不兼容的数据类型转换为另一种类型,会出现TypeError。下面是一些示例:

  1. 整数到浮点数
    1. int_value = 5
    2. float_value = int_value + .01 # 尝试添加一个小数部分
    3. print(float_value) # 输出: 5.01
  2. 字符串到整数
    1. str_value = "123"
    2. try:
    3. int_value = int(str_value) # 尝试将字符串转换为整数
    4. except ValueError as e:
    5. print(f"Error: {e}, Unable to convert string to integer") # 输出:错误: invalid literal for int() with base 10, 不能将字符串转换为整数
  3. 列表到字典
    1. list_value = [('Name', 'John'), ('Age', 25)]
    2. try:
    3. dict_value = dict(list_value[0]) # 尝试将列表中的元素转化为字典
    4. except TypeError as e:
    5. print(f"Error: {e}, Unable to convert list to dictionary") # 输出:错误: unhashable type: 'list', 不能将列表转换为字典
    以上示例展示了如何在Python中进行类型转换,如果转换失败会抛出TypeError。
文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,30人围观)

还没有评论,来说两句吧...

相关阅读