简体   繁体   English

在python词典中用'替换'\\ n'

[英]Replace '\n' with '' in python dictionary

I'm reading from dataset with json objects, in dataset some of values has abcd\\nabdc format. 我正在从具有json对象的数据集中读取,在数据集中某些值具有abcd \\ nabdc格式。 I used following code: 我使用以下代码:

for line in open("c:\\dataset","r+").readlines():
       d= json.loads(line)
       str1 = d['strkey1']
       str1.replace('\n' , '')

but it fails to replace. 但无法替换。

d['strkey1'] = d['strkey1'].replace('\n', '')

Strings are immutable, so string methods return new strings, not modifying the original. 字符串是不可变的,因此字符串方法返回新的字符串, 而不修改原始字符串。

Also: 也:

for line in open("c:\\dataset","r+"):

Will suffice, you don't need to .readlines() the whole file into memory before going through each line. 足够了,您不需要在遍历每一行之前将整个文件.readlines()放入内存。 But that still isn't enough, you need to remember to close your files, a with statement will handle that for you: 但这还不够,您需要记住关闭文件, with语句将为您处理:

with open("c:\\dataset","r+") as f:
    for line in f:
        # do stuff

Just change your code to: 只需将代码更改为:

for line in open("c:\\dataset","r+").readlines():
       dict = json.loads(line)
       dict['strkey1'] = dict['strkey1'].replace('\n','')

This works and your's doesn't as strings are immutable (they can't be changed), so string methods return a new string, (which here you need to store) 这行得通,因为字符串是不可变的(不能更改),所以您的字符串不可变,因此字符串方法将返回新的字符串(您需要在此处存储)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM