无法在dict:keys中清除空格和\ n字符

问题描述 投票:-3回答:1

在python中填充包含字符串的字典

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

我不可能删除空格和换行符。我发现的每个解决方案都包含使用方法.rstrip()或类似replace(' ', '')的dict。

要么:

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

它导致了

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

这不起作用。有解决方案吗?

我正在使用Python 3.7

python python-3.x dictionary removing-whitespace
1个回答
0
投票

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

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

   # removes the '\n' 
   for element in myDict:
      templist.append(element.rstrip('\n'))
      #print(element) 
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.