我试图从python字典中删除所有\ r \n.最简单的方法是什么?我的字典目前看起来像这样 -
{'': '34.8\r\n',
'Mozzarella di Giovanni\r\n': '34.8\r\n',
'Queso Cabrales\r\n': '14\r\n',
'Singaporean Hokkien Fried Mee\r\n': '9.8\r\n'
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是我正在尝试的 -
for key, values in productDictionary.items() :
key.strip()
values.strip()
key.strip('"\"r')
key.strip('\\n')
values.strip('\\r\\n')
print productDictionary
Run Code Online (Sandbox Code Playgroud)
输出仍然是相同的.
你可以使用str.strip():
str.strip() 当没有参数使用时,删除所有类型的前导和尾随空格.
>>> productDictionary={'': '34.8\r\n',
'Mozzarella di Giovanni\r\n': '34.8\r\n',
'Queso Cabrales\r\n': '14\r\n',
'Singaporean Hokkien Fried Mee\r\n': '9.8\r\n'
}
>>> productDictionary=dict(map(str.strip,x) for x in productDictionary.items())
>>> print productDictionary
>>>
{'': '34.8',
'Mozzarella di Giovanni': '34.8',
'Queso Cabrales': '14',
'Singaporean Hokkien Fried Mee': '9.8'}
Run Code Online (Sandbox Code Playgroud)
help() 上 str.strip()
S.strip([chars]) - >字符串或unicode
返回字符串S的副本,其中删除了前导和尾随空格.如果给出了chars而不是None,则删除chars中的字符.如果chars是unicode,则S将在剥离之前转换为unicode
使用字典理解:
clean_dict = {key.strip(): item.strip() for key, item in my_dict.items()}
Run Code Online (Sandbox Code Playgroud)
该strip()函数从字符串的正面和背面删除换行符,空格和制表符.