gpt4 book ai didi

python - 我如何在我的代码中正确使用替换功能?

转载 作者:行者123 更新时间:2023-11-28 22:15:44 24 4
gpt4 key购买 nike

我试图从外部文件中删除每一行的\n,然后将该行拆分为 2 个列表。但是,当代码运行无误时,替换函数不会替换任何内容。

infile = open('Kaartnummers.txt', 'r')
field1 = []
field2 = []
for items in infile:
items.replace('\n', '')
fields = items.split(", ")
field1.append(fields[0])
field2.append(fields[1])


print(field1, field2)


infile.close()

外部文件包含以下内容:

325255, Jan Jansen
334343, Erik Materus
235434, Ali Ahson
645345, Eva Versteeg
534545, Jan de Wilde
345355, Henk de Vries

最佳答案

Python 中的字符串是不可变的,因此 replace 方法无法原地工作。它返回一个新字符串,而不是更改现有字符串。尝试:

items = items.replace('\n', '') # save the return value from the replace call

或者,也许您应该使用一种更具体的方法(从字符串末尾删除特定字符):

items = items.rstrip('\n') # or just .strip() if you don't mind removing other whitespace

关于python - 我如何在我的代码中正确使用替换功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52673732/

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