python - 如何从 Python 字典中的键中删除尾随空格?

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

https://stackoverflow.com/questions/65531913/

相关文章:

hash - 如何从 elixir 中的 map 创建 `hash` 或 `md5`?

scala - 基于Map从List[String]转换为List[Int]

python - Pandas:如何用另一个值替换 int 子字符串

java - 更正应包含单个兼容版本的应用程序的类路径

reactjs - firebase safari 错误消息 : This browser does

node.js - 如何动态地从 Firestore 数组中删除多个元素?

java - JDBC 向数据库中插入变量

c - STM32创建RAM段

typescript - TypeScript 如何推断回调参数类型

r - 无法为 R 中的列表替换 NA 的拼写错误