【问题标题】:How to replace a certain character from values of dicts in a list?如何从列表中的字典值中替换某个字符?
【发布时间】:2019-03-18 17:01:46
【问题描述】:

我正在尝试替换给定列表中的某个字符,但出现此错误:

AttributeError: 'list' object has no attribute 'replace'

我该如何解决这个问题?

String=[{"id":"id1 \n\n","key2 \n":"value2","key3":"value3"},{"id":"id2","key2":"value2","key3":"value3"},{"id":"id3","key2":"value2","key3":"value3't"}]

new_str = String.replace('\n', '')

new_str = String.replace("'", '')
print new_str

【问题讨论】:

  • String 是字典对象的列表,列表对象没有替换方法。您确定要将 String 初始化为您想要的值吗?

标签: python string python-2.7 replace


【解决方案1】:

您问题中的字符串实际上是字典元素的列表。
而且列表也没有替换方法。所以这是行不通的。
由于您要替换每个键和值的新行,因此您必须遍历列表的每个元素和字典的每个键值对并替换字符串。

list_of_dicts = [{"id" : "id1 \n\n", "key2 \n" : "value2", "key3" : "value3"},{"id" : "id2", "key2" : "value2", "key3" : "value3"},{"id" : "id3", "key2" : "value2", "key3" : "value3't"}
    ]

new_list_of_dicts = [dict([(key.replace("\n", ""), dict1[key].replace("\n", "")) for key in dict1]) for dict1 in list_of_dicts]

print new_list_of_dicts


输出:

[{'key3': 'value3', 'key2 ': 'value2', 'id': 'id1 '}, {'key3': 'value3', 'key2': 'value2', 'id': 'id2'}, {'key3': "value3't", 'key2': 'value2', 'id': 'id3'}]

【讨论】:

  • 嗨,Shirish 感谢您的回复和帮助。你能告诉我如何用“value3't”替换“value3't”吗?
  • 在替换函数中使用 value3't 代替 \n
【解决方案2】:

你有一个字典数组。所以我们需要先迭代数组。然后我们需要用正确的键和值制作一个新的字典,然后用新的项目填充字典。

    String=[{"id":"id1 \n\n","key2 \n":"value2","key3":"value3"},{"id":"id2","key2":"value2","key3":"value3"},{"id":"id3","key2":"value2","key3":"value3't"}]

for dic in String: 'iterating the array
    newdic = {} 'a new dictionary to stroe corrected pairs
    for item in dic.items():
        'making a new pair with corrected key and value
        key = item[0].replace('\n', '').replace("'", '')
        val = item[1].replace('\n', '').replace("'", '')
        newdic.update({key:val})
    ' now replace the dictionary items
    dic.clear()
    dic.update(newdic) 

【讨论】:

    【解决方案3】:

    您所拥有的是dictionaries 中的list 而不是string,您需要遍历每个字典中的keysvalues 来完成此操作

    lst = [{k.strip(): v.strip().replace("'","") for k, v in i.items()} for i in lst]
    # [{'id': 'id1', 'key2': 'value2', 'key3': 'value3'}, {'id': 'id2', 'key2': 'value2', 'key3': 'value3'}, {'id': 'id3', 'key2': 'value2', 'key3': 'value3t'}]
    

    展开

    res = []
    for i in lst:
        x = {}
        for k, v in i.items():
            x[k.strip()] = v.strip().replace("'","")
        res.append(x)
    print(res)
    

    【讨论】:

    • 嗨,@vash_the_stampede 非常感谢您的回复和帮助
    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2023-01-08
    • 2019-09-30
    • 2010-11-07
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多