Home > Mobile >  why do string.strip() function removed the character i want in some words and remove none in others
why do string.strip() function removed the character i want in some words and remove none in others

Time:04-19

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:

['Aang\n', 'Zuko\n', 'Appa\n', 'Katara\n', 'Sokka\n', 'Momo\n', 'Uncle Iroh\n', 'Toph']
['Zuko\n', 'Katara\n', 'Momo\n', 'Toph', 'Appa', 'Uncle Iroh', 'Sokka', 'Aang']

CodePudding user response:

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.)

  • Related