在字典中删除 \n

removing \n in dictionary

我在删除程序中的 \n 时遇到问题,这里是代码

with open(filename) as f:
    for line in f.readlines():
        parent, child = line.split(",")
            parent.strip()
            child.strip()
            children[child].append(parent)

尝试使用 .rstrip 和其他变体,但它对我没有任何作用,这就是我得到的结果

{'Patricia\n': ['Mary'], 'Lisa\n': ['Mary']} 

问题是当我调用 children["Patricia"] 我得到 [],因为它只识别 children["Patricia\n"]

请在split之前使用strip:

parent, child = line.rstrip("\n").split(",")

问题是:parent.strip() 需要重新分配给一个字符串,因为字符串是不可变的。

单独调用 strip() 不会更改原始值。您需要首先分配给一个变量,或者在您的字典创建中使用它。

看看下面的代码片段是否能解决您的问题

with open(filename) as f:
    for line in f.readlines():
        parent, child = line.split(",")
            children[child.strip()].append(parent.strip())

其实,你们很亲近。字符串是不可变的,因此调用 strip() 将 return 一个新字符串,同时保持原始字符串不变。

所以替换

parent.strip()
child.strip()

parent = parent.strip()
child = child.strip()

会成功的。