strip char from list of strings

Piet van Oostrum piet at cs.uu.nl
Tue May 19 04:25:35 EDT 2009


>>>>> Laurent Luce <laurentluce49 at yahoo.com> (LL) wrote:

>LL> I have the following list:

>LL> [ 'test\n', test2\n', 'test3\n' ]

>LL> I want to remove the '\n' from each string in place, what is the
>LL> most efficient way to do that ? 

I suppose you mean you have lists similar to the one given because with
a list of 3 elements efficiency is a non-issue unless you do something
stupid or repeat the operation thousands of times. Even with a list of
1000 elements efficiency isn't very important. In fact you should worry
about efficiency only after there are signs that there might be a
problem. 

Secondly, in Python you cannot remove a character from a string in place
if that means modifying the string. Strings are immutable. So let us
suppose you mean that the list should stay in place, i.e if L is the
list that after the operation L is still the same object but L[i]
has become a string that has the value of the old L[i] with the '\n'
removed. Let us also suppose that in the original list every element has
exactly one '\n' at the end.

Then a simple loop should do it. The enumerate comes to mind as you need
both the index and the value of each element:

for i, value in enumerate(L):
    L[i] = value[:-1]

But it looks a bit silly to me to refer to the same list element as both
value and L[i]. So maybe the old-fashioned way is more clear:

for i in range(len(L)):
    L[i] = L[i][:-1]

I think the choice is a matter of taste. You can do some timing
experiments yourself to see if there are significant differences, but I
wouldn't expect so.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list