Issue
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']
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!
Answered By - The Myth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.