【问题标题】:Add and increment number to the end of numerical or non-numerical string python在数字或非数字字符串python的末尾添加和增加数字
【发布时间】:2016-03-21 14:12:05
【问题描述】:

我正在读取一个包含数据的 JSON 文件,并试图确保在我的代码中创建的每个文件都具有唯一值。但是有时该值是一个字符串,例如“数据”或某个数字作为字符串

因此,如果我创建 3 次的文件称为“数据”,我想将其转换为:

data_0
data_1
data_2

另外,如果值是一个数字(但它是字符串格式),例如 145,我想将其更改为:

145
146
147 

目前我的代码会产生这样的结果:

data_0, 
data_0_1, 
data_0_1_2

145_0, 
145_0_1, 
145_0_1_2

下面是我的代码:

for index in range(0,len(test)):
      test[index]["value"]= test[index]["value"] + str(number)

我正在使用str(number),否则我会收到此错误:

TypeError: coercing to Unicode: need string or buffer, int found

JSON 文件示例:

"test": [{
    "type": "text",
    "value": "data"
}, {
    "type": "integer",
    "value": "145"
}]

任何建议将不胜感激。

【问题讨论】:

  • 请添加test的内容。
  • @Borja 我已经添加了测试的内容
  • @Borja 这是我在 python 中导入和读取的 json 文件,它对我来说可以正常工作。也就是json格式。
  • 这是您第一次在帖子中提到 json 这个词。请务必非常具体。
  • 你能澄清一下这个问题吗?你的代码有什么问题?您希望如何改进它?

标签: python json string


【解决方案1】:

您可以使用try & catch 来检查输入是整数还是字符串。如果是 int,则将数字加 1,如果是 string,则只需附加 _index

test = [{"type": "text", "value": "data"}, {"type": "integer","value": "145"}]

for index in range(0,len(test)):
    try:
        # Test if the value is an integer
        test[index]["value"]= int(test[index]["value"]) + index

    except ValueError:
        # The value is an string
        test[index]["value"]= test[index]["value"] + "_" + str(index)

print test

输出:

[{'type': 'text', 'value': 'data_0'}, {'type': 'integer', 'value': 146}]

【讨论】:

    【解决方案2】:

    Borja 的回答很好,遵循EAFP 原则。如果您使用enumeratestr.format,您的代码可以稍微清理一下。

    for index, dictionary in enumerate(test):
        try:
            dictionary['value'] = int(dictionary['value']) + 1
    
        except ValueError:
            dictionary['value'] += '_{}'.format(index)
    

    【讨论】:

      猜你喜欢
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      相关资源
      最近更新 更多