I have a list of strings, some of them ends with new line symbol. I want to modify this list by removing \n from strings which ends with it. For this purpose I use the following code:
aList = ['qwerttyy\n', '123454\n', 'zxcv']
for s in aList:
if s.endswith('\n'):
s = s[: -1]
print(s)
The output is the following:
qwerttyy
123454
>>> aList
['qwerttyy\n', '123454\n', 'zxcv']
So the original list wasn't changed though list is mutable object. What is the reason of such behavior?
You can use slice assignment and a list comprehension:
>>> foo = aList = ['qwerttyy\n', '123454\n', 'zxcv']
>>> aList[:] = [s[:-1] if s.endswith('\n') else s for s in aList]
>>> foo #All references are affected.
['qwerttyy', '123454', 'zxcv']
>>> aList
['qwerttyy', '123454', 'zxcv']
Your code didn't work because it is equivalent to:
s = aList[0]
if s.endswith('\n'):
s = s[: -1]
s = aList[1]
if s.endswith('\n'):
s = s[: -1]
...
i.e You're updating the variable s, not the actual list item
because the for loop makes copies of strings.
You can use:
[s[:-1] if s.endswith('\n') else s for s in aList]
Maybe this is simpler, though it will remove also whitespaces.
[s.strip() for s in aList]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With