Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. Calling file.readlines() results in a list of all of the countries with \n included at the end of each line. I intend to use rstrip("\n") to remove the character from each item in the list.

The intended result is achieved when I use this while loop:

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But it doesn’t work when I use this for loop:

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’]

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.

I would really appreciate some insight on what mistake I made here. Thanks!

>Solution :

The mistake you have made here is that you are stripping the ‘\n’ properly. 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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading