我正在从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
列表
我真的很想知道我在这里犯了什么错误。谢谢