【问题标题】:how to convert int with str('123') to int如何将带有 str('123') 的 int 转换为 int
【发布时间】:2020-01-05 07:55:09
【问题描述】:

例如,之前:

a = {'a': '1234', 'b': 'asdf', 'c': '456'}

之后:

a = {'a': 1234, 'b': 'asdf', 'c': 456}

旋转a,如果可以转换成int,我想制作int

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来解决问题?

标签: python-3.x string int converters


【解决方案1】:
a = {'a': '1234', 'b': 'asdf', 'c': '456'}
for i in a:
    try:
        b=int(a[i])
        a[i]=b
    except:
        pass

print(a)

事实上try/except 是巨魔,但它是另一种方式。

【讨论】:

    【解决方案2】:

    dict-comprehension 对这项任务很有用,您可以在将字符串转换为 int 之前使用 str.isdigit() 检查字符串是否为数字:

    new_a = {k : int(v) if v.isdigit() else v for k, v in a.items()} 
    
    print(new_a)
    

    输出:

    {'a': 1234, 'b': 'asdf', 'c': 456}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      相关资源
      最近更新 更多