简体   繁体   English

从字典中删除特殊字符

[英]Removing special characters from dictionary

I am trying to remove all the \\r\\n from the python dictionary.我正在尝试从 python 字典中删除所有 \\r\\n 。 What is the easiest way to do so.这样做的最简单方法是什么。 My dictionary is looking like this at the moment -我的字典现在是这样的——

 {'': '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'
}

EDIT : Here's what I'm trying -编辑:这就是我正在尝试的-

for key, values in productDictionary.items() :
    key.strip()
    values.strip()
    key.strip('"\"r')
    key.strip('\\n')
    values.strip('\\r\\n')
print productDictionary

And the output is still the same.而且输出还是一样的。

Using a dictionary comprehension:使用字典理解:

clean_dict = {key.strip(): item.strip() for key, item in my_dict.items()}

The strip() function removes newlines, spaces, and tabs from the front and back of a string. strip()函数从字符串的前后删除换行符、空格和制表符。

you can use str.strip() :你可以使用str.strip()

str.strip() when used with no arguments, strips all types of leading and trailing whitespaces. 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'}

help() on str.strip() help()str.strip()

S.strip([chars]) -> string or unicode S.strip([chars]) -> 字符串或 unicode

Return a copy of the string S with leading and trailing whitespace removed.返回删除前导和尾随空格的字符串 S 的副本。 If chars is given and not None, remove characters in chars instead.如果给出了 chars 而不是 None,则删除 chars 中的字符。 If chars is unicode, S will be converted to unicode before stripping如果 chars 是 unicode,则 S 将在剥离前转换为 unicode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM