繁体   English   中英

如何从 Python 字典中的键中去除尾随空格?

[英]How to strip trailing space from keys in a Python Dictionary?

我在名为“ 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

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

谢谢!

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

尝试改变:

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

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

你可以替换这个:

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

这样:

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

只是改变

users[key] = value

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM