python - 从 Dicts Python 3 中去除换行符

标签 python python-3.x dictionary strip

如何从 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/

相关文章:

python - 如何使用python bottle框架查询mongo数据库

c# - 玩家卡牌收集 MySQL

java - Android 中的 NSDiacriticInsensitiveSearch 等价物

python - 无法将 pandas Series 传递给 pyplot 的 fill_ Between 函数?

Python 过滤器没有按预期工作?

python - 使用 Python 从原始帧创建 MPEG4 视频文件

Python调用脚本而不等待它执行

python-3.x - 如何从存储在字典列表中的 Facebook 评论中提取回复?

python - 无法解析网页中的不同产品链接

python - 在 python 中操作 Google Cloud Firestore 数据