从Dicts Python 3中删除换行符

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Dicts Python 3中删除换行符相关的知识,希望对你有一定的参考价值。

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

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

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

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

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

testDict = {key: value.rstrip() for key, value in testDict.items()}
另一答案

使用字典理解:

testDict = {key: value.strip('
') for key, value in testDict.items()}
另一答案

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

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

那就行了。

以上是关于从Dicts Python 3中删除换行符的主要内容,如果未能解决你的问题,请参考以下文章