-1

I am trying to remove \n in my list, but unfortunately my code does not work.

mylist = ['\nHello', 'This', 'Is A', 'List']

for items in mylist:
    if "\n" in items:
        items.replace("\n", "")

print(mylist)

Is there a way to remove a letter in a string, that is in a list?

K Doe
  • 17
  • 2
  • 3
    `replace` returns a new string, but you're not assigning it to anything. – Robert Harvey Dec 07 '18 at 20:29
  • 2
    you never assigned the result of `items.replace("\n", "")` – Paritosh Singh Dec 07 '18 at 20:30
  • 1
    You are probably looking for `items.strip()` – Akavall Dec 07 '18 at 20:30
  • @RobertHarvey I don't think that's the best dupe tbh. [This](https://stackoverflow.com/questions/19290762/cant-modify-list-elements-in-a-loop-python/19290848) works with looping through a list (the top answer isn't great). The result still has to be assigned back to a list item and your dupe doesn't (I don't think?) cover that – roganjosh Dec 07 '18 at 20:32
  • @k-doe try `mylist = [item.strip('\n') for item in mylist]` – chickity china chinese chicken Dec 07 '18 at 20:34
  • more accurate dupe may be [How to remove \n from a list element?](https://stackoverflow.com/questions/3849509/how-to-remove-n-from-a-list-element) – chickity china chinese chicken Dec 07 '18 at 20:36
  • @davedwards item.strip('\n') will strip any occurence of "\" and "n", that's probably not what is expected. in order to strip the sequence of "\" and "n", you need to use `str.replace('\n','')`. Something as follows e.g.: `mylist = [e.replace('\n', '') for e in mylist]` – olisch Dec 07 '18 at 20:38

1 Answers1

0

You could use map

mylist = ['\nHello', 'This', 'Is A', 'List']
list(map(str.strip,mylist))
mad_
  • 8,121
  • 2
  • 25
  • 40