[英]Python - reading and manipulating list from file.readlines() behaves differently in a for loop than in a while loop
I'm reading a list of all countries from a txt file.我正在从一个 txt 文件中读取所有国家/地区的列表。 Calling
file.readlines()
results in a list of all of the countries with \n
included at the end of each line.调用
file.readlines()
会生成所有国家/地区的列表,每行末尾都包含\n
。 I intend to use rstrip("\n")
to remove the character from each item in the list.我打算使用
rstrip("\n")
从列表中的每个项目中删除字符。
The intended result is achieved when I use this while loop:当我使用这个 while 循环时,达到了预期的结果:
file = open("countries.txt")
countries = file.readlines()
file.close()
i = 0
while i < len(countries):
countries[i] = countries[i].rstrip("\n")
i += 1
print(countries[:4])
Output: ['Afghanistan', 'Albania', 'Algeria', 'Andorra'] Output:['阿富汗','阿尔巴尼亚','阿尔及利亚','安道尔']
But it doesn't work when I use this for loop:但是当我使用这个 for 循环时它不起作用:
file = open("countries.txt")
countries = file.readlines()
file.close()
for country in countries:
country = country.rstrip("\n")
print(countries[:4])
Output: ['Afghanistan\n', 'Albania\n', 'Algeria\n', 'Andorra\n'] Output: ['阿富汗\n', '阿尔巴尼亚\n', '阿尔及利亚\n', '安道尔\n']
Using a debugger, I was able to see that during the for loop, the \n
is correctly stripped from the string, but the resulting string is not changed in the countries
list.使用调试器,我能够看到在 for 循环期间,
\n
被正确地从字符串中删除,但结果字符串在countries
列表中没有改变。
I would really appreciate some insight on what mistake I made here.对于我在这里犯的错误,我真的很感激。 Thanks!
谢谢!
The mistake you have made here is that you are stripping the '\n' properly.你在这里犯的错误是你正确地剥离了'\n'。 But, you aren't saving it in the list, this code is basically updating the 'country' variable and has no impact to the list you are printing (countries) because it is not saving the changes.
但是,您并没有将它保存在列表中,这段代码基本上是在更新“国家”变量,并且对您正在打印的列表(国家)没有影响,因为它没有保存更改。 Here's what you should do:
这是你应该做的:
for i, country in enumerate(countries):
countries[i] = country.rstrip('\n')
This code should work perfectly fine!这段代码应该工作得很好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.