Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典中删除特殊字符_Python_Dictionary - Fatal编程技术网

Python 从字典中删除特殊字符

Python 从字典中删除特殊字符,python,dictionary,Python,Dictionary,我正在尝试从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' } 编辑:以下是我正在尝试的内容- for key, values in productDiction

我正在尝试从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'
}
编辑:以下是我正在尝试的内容-

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

输出仍然相同。

您可以使用
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()

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

返回带前导和尾随空格的字符串S的副本 远离的。如果给定了字符而不是无,请删除字符中的字符 相反如果字符是unicode,则在 剥离


您可以使用
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()

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

返回带前导和尾随空格的字符串S的副本 远离的。如果给定了字符而不是无,请删除字符中的字符 相反如果字符是unicode,则在 剥离


使用字典理解:

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

strip()
函数用于删除字符串前后的换行符、空格和制表符。

使用字典理解:

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

strip()
函数删除字符串前后的换行符、空格和制表符。

@AshishAgarwal您所做的不正确,我的代码工作正常。@AshishAgarwal您所做的不正确,我的代码工作正常。在您的代码中,您实际上是在一个列表(
.items()
)上迭代,修改从此列表中检索的变量不会影响dict。Strip返回已删除这些字符的字符串,但不会修改该字符串。在代码中,您实际上是在列表(
.items()
)上迭代,修改从此列表中检索到的变量不会影响
dict
。Strip返回一个删除了这些字符的字符串,它不会修改该字符串。@AshwiniChaudhary--哎呀,我修复了它。键和项之间需要一个冒号,而不是逗号。@AshwiniChaudhary——哎呀,我修好了。在键和项之间需要一个冒号,而不是逗号。