strip char from list of strings

Jorgen Grahn grahn+nntp at snipabacken.se
Tue May 19 12:11:33 EDT 2009


On Tue, 19 May 2009 10:25:35 +0200, Piet van Oostrum <piet at cs.uu.nl> wrote:
>>>>>> 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 the best way is probably to make sure the '\n's do not end up in
the list in the first place. I suspect that is often more elegant too.

/Jorgen

-- 
  // Jorgen Grahn <grahn@        Ph'nglui mglw'nafh Cthulhu
\X/     snipabacken.se>          R'lyeh wgah'nagl fhtagn!



More information about the Python-list mailing list