簡體   English   中英

從字典中刪除特殊字符

[英]Removing special characters from 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 productDictionary.items() :
    key.strip()
    values.strip()
    key.strip('"\"r')
    key.strip('\\n')
    values.strip('\\r\\n')
print productDictionary

而且輸出還是一樣的。

使用字典理解:

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

strip()函數從字符串的前后刪除換行符、空格和制表符。

你可以使用str.strip()

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()str.strip()

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

返回刪除前導和尾隨空格的字符串 S 的副本。 如果給出了 chars 而不是 None,則刪除 chars 中的字符。 如果 chars 是 unicode,則 S 將在剝離前轉換為 unicode

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM