Py学习  »  Python

Python——从文件中读取和操作列表。readlines()在for循环中的行为与在while循环中的行为不同

Victor • 3 年前 • 1252 次点击  

我正在从txt文件中读取所有国家的列表。使命感 file.readlines() 结果列出了所有 \n 包含在每行末尾。我打算使用 rstrip("\n") 从列表中的每个项目中删除字符。

当我使用这个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])

输出:[阿富汗、阿尔巴尼亚、阿尔及利亚、安道尔]

但当我使用这个for循环时,它不起作用:

file = open("countries.txt")
countries = file.readlines()
file.close()
for country in countries:
    country = country.rstrip("\n")
print(countries[:4])

输出:[“阿富汗”、“阿尔巴尼亚”、“阿尔及利亚”、“安道尔”]

使用调试器,我能够在for循环期间看到 \n 正确地从字符串中剥离,但在 countries 列表

我真的很想知道我在这里犯了什么错误。谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129002
 
1252 次点击  
文章 [ 1 ]  |  最新文章 3 年前