i am trying to remove the ‘n’ characters a string because when i read the lines from a file it include the ‘n’ characters!! input:
with open('names.txt', mode='r') as file: list_of_names = file.readlines() print(list_of_names) for name in list_of_names: list_of_names.remove(name) name = name.strip('n') list_of_names.append(name) print(list_of_names)
output:
['Aangn', 'Zukon', 'Appan', 'Kataran', 'Sokkan', 'Momon', 'Uncle Irohn', 'Toph'] ['Zukon', 'Kataran', 'Momon', 'Toph', 'Appa', 'Uncle Iroh', 'Sokka', 'Aang']
Advertisement
Answer
Because you are modifying the list while iterating over it, halfway through the loop, list_of_names.remove(name)
is trying to remove the wrong element. This is also why the order of the list changes. This is unnecessarily complex.
Instead of modifying the old list, consider simply appending to a new, empty list.
with open('names.txt', mode='r') as f: list_of_names = f.readlines() new_list_of_names = [] print(list_of_names) for name in list_of_names: name = name.strip('n') new_list_of_names.append(name) print(new_list_of_names)
Or, for shorter code, use list comprehension:
with open('names.txt') as f: list_of_names = f.readlines() new_list_of_names = [name.strip('n') for name in list_of_names] print(list_of_names) print(new_list_of_names)
(Note: mode='r'
is redundant because the default mode is read.)