如何从 Python 中的字典值中删除 \n
或换行符?
testDict = {'salutations': 'hello', 'farewell': 'goodbye\n'}
testDict.strip('\n') # 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()}
关于python - 从 Dicts Python 3 中去除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41913605/