gpt4 book ai didi

Python strip() 不适用于新行

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:09 26 4
gpt4 key购买 nike

在我从测试文件中获取数据后,我尝试删除“\n”,但我仍然在输出中看到新行。

users_data = open('users.txt', 'r')
line = users_data.readline()
while line:
line.strip('\n')
metode, data = line.split(":")
d = {} #for debuging
d[metode]=data
print(d)
line = users_data.readline()

我将它们放入字典中进行调试,然后我得到:

{'gender': 'f\n'}
{'name': 'elise\n'}

我是不是做错了什么?

最佳答案

因为字符串是不可变的,line.strip() 根本不会做任何事情。 strip() 不是原地操作,它会返回一个新的字符串。

line = line.strip()

就是你想要的。

关于Python strip() 不适用于新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19176468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com