【问题标题】:Can't cleanup whitespace and \n chars in dict:keys无法清除 dict:keys 中的空格和 \n 字符
【发布时间】:2019-09-18 13:05:21
【问题描述】:

在python3中填充包含类似字符串的字典

'  \n                    \n                      \n                        \n                          \n   '

我无法删除空格和换行符。我找到的每个解决方案都包含使用方法 .rstrip() 或类似 replace(' ', '') 的方法。

或者:

for key, value in dict.items():
    dict[key] = value.rstrip()

结果

AttributeError: 'list' object has no attribute 'rstrip'

这行不通。有什么解决办法吗?

我正在使用 Python 3.7

【问题讨论】:

  • 您在值而不是键上调用 rstripnew_dict = {key.rstrip(): value for key, value in old_dict.items()} 或类似的。重建字典。

标签: python python-3.x dictionary removing-whitespace


【解决方案1】:

如果你想对你的字典的每个值使用 rstrip(),你可以使用 forloop:

   templist = []
   myDict = {'hi', 'this \n'}

   # removes the '\n' 
   for element in myDict:
      templist.append(element.rstrip('\n'))
      #print(element) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多