从字典中去除​​换行符 Python 3

Stripping Newline Characters From Dicts Python 3

如何从 Python 中的字典值中删除 \n 或换行符?

testDict = {'salutations': 'hello', 'farewell': 'goodbye\n'}
testDict.strip('\n') # I know this part is incorrect :)
print(testDict)

使用字典理解:

testDict = {key: value.strip('\n') for key, value in testDict.items()}

要更新字典 in-place,只需遍历它并将 str.rstrip() 应用于值:

for key, value in testDict.items():
    testDict[key] = value.rstrip()

要创建新词典,您可以使用词典理解:

testDict = {key: value.rstrip() for key, value in testDict.items()}

您正在尝试从字典对象中删除换行符。 您想要的是遍历所有 Dictionary 键并更新它们的值。

for key in testDict.keys():
    testDict[key] = testDict[key].strip()

这样就可以了。