【问题标题】:How to strip trailing space from keys in a Python Dictionary?如何从 Python 字典中的键中去除尾随空格?
【发布时间】:2021-01-01 17:20:16
【问题描述】:

我在名为“user_table.txt”的文本文件中有以下数据:

Jane - valentine4Me
Billy 
Billy - slick987
Billy - monica1600Dress
 Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
   Charlotte - beutifulGIRL!
  Christoper - chrisjohn

并且,下面的代码用来读取这些数据并创建一个 Python 字典:

users = {}

with open("user_table.txt", 'r') as file:
    for line in file:
        line = line.strip()
    
        # if there is no password
        if ('-' in line) == False:
            continue
    
        # otherwise read into a dictionary
        else:
            key, value = line.split('-')
            users[key] = value
            
k= users.keys()
print(k)

if 'Jane' in k:
    print('she is not in the dict')
if 'Jane ' in k:
    print('she *is* in the dict')

我看到键中有尾随空格:

dict_keys(['Jane ', 'Billy ', 'Jason ', 'Brian ', 'Laura ', 'Charlotte ', 'Christoper '])
she *is* in the dict

删除空格的最佳方法是什么?

谢谢!

【问题讨论】:

标签: python io


【解决方案1】:

key, value = line.split('-') 更改为key, value = line.split(' - ')

【讨论】:

    【解决方案2】:

    尝试改变:

    key, value = line.split('-')
    

    key, value = [i.strip() for i in line.split('-')]
    

    【讨论】:

      【解决方案3】:

      你可以替换这个:

      key, value = line.split('-')
      users[key] = value
      

      通过这个:

      k=line.split('-')
      users[k[0].strip()]=k[1]
      

      【讨论】:

        【解决方案4】:

        只是改变

        users[key] = value
        

        users[key.strip()] = value.strip()
        

        这将概括您的代码,以防 split() 中“-”的任一侧或两侧没有空格。

        【讨论】:

          猜你喜欢
          • 2021-10-22
          • 2011-08-28
          • 2017-01-22
          • 2011-10-02
          • 1970-01-01
          • 2019-12-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多