从Dicts Python 3中删除换行符

问题描述 投票:2回答:3

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

testDict = {'salutations': 'hello', 'farewell': 'goodbye\n'}
testDict.strip('\n') # I know this part is incorrect :)
print(testDict)
python python-3.x dictionary strip
3个回答
3
投票

要就地更新字典,只需迭代它并将str.rstrip()应用于值:

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

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

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

2
投票

使用字典理解:

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

0
投票

您正试图从Dictionary对象中删除换行符。你想要的是迭代所有字典键并更新它们的值。

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

那就行了。

© www.soinside.com 2019 - 2024. All rights reserved.