D. *_* K. 6 python whitespace dictionary python-3.x
我在我的程序中删除\n有问题这里是代码
with open(filename) as f:
for line in f.readlines():
parent, child = line.split(",")
parent.strip()
child.strip()
children[child].append(parent)
Run Code Online (Sandbox Code Playgroud)
尝试使用.rstrip和其他变种,但它对我没有任何作用,这是我得到的结果
{'Patricia\n': ['Mary'], 'Lisa\n': ['Mary']}
Run Code Online (Sandbox Code Playgroud)
问题是,当我打电话给孩子["Patricia"]我得到[],因为它只识别孩子["Patricia \n"]
实际上,你很亲密.字符串是不可变的,因此调用strip()将返回一个新字符串,同时保留原始字符串.
所以更换
parent.strip()
child.strip()
Run Code Online (Sandbox Code Playgroud)
同
parent = parent.strip()
child = child.strip()
Run Code Online (Sandbox Code Playgroud)
会做的伎俩.
请使用strip之前split:
parent, child = line.rstrip("\n").split(",")
Run Code Online (Sandbox Code Playgroud)
问题是:parent.strip()需要重新分配给字符串,因为字符串是不可变的.