1

I have the following list :

mylist = ["test1","test2","test3\n"]

I am trying to remove the \n in the last element, here is how i tried :

mylist = ["test1","test2","test3\n"]
print(mylist)
> ['test1', 'test2', 'test3\n']

mylist[-1].strip("\n") # trying with .replace("\n", "") don't work too
print(mylist)
> ['test1', 'test2', 'test3\n']

I miss why it doesn't work, i can't use strip or replace on an element of a list ? Only a string ?

PS : mylist[-1] is the right element, but as you can see, \n is interpreted :

print(mylist[-1])
> test3

Sorry for possible duplicate, i couldn't find my error.

molik
  • 51
  • 5
  • 4
    `strip` doesn't act in-place, it returns the new string. `replace` does the same. – Kemp Feb 23 '21 at 14:45

1 Answers1

2

Strings are immutable. Running .strip() (or any str method, for that matter, including .replace()) doesn't change the original string. Do mylist[-1] = mylist[-1].strip("\n")

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70