strip char from list of strings

Laurent Luce laurentluce49 at yahoo.com
Tue May 19 16:56:35 CEST 2009


Thanks Casey. I like your solution.

Casey Webster wrote:
> On May 18, 3:30 pm, Laurent Luce <laurentluc... at yahoo.com> wrote:
>> I have the following list:
>>
>> [ 'test\n', test2\n', 'test3\n' ]
>>
>> I want to remove the '\n' from each string in place, what is the most efficient way to do that ?
>>
>> Regards,
>>
>> Laurent
> 
> Do you _really_ need to do this in place?  If not, the simplest answer
> is probably:
> 
>>>> x = ['test\n', test2\n', 'test3\n']
>>>> x = [s.rstrip('\n') for s in x]
> 
> And if what you really want to do is strip off all trailing whitespace
> (tabs, spaces, and newlines), then:
> 
>>>> x = [s.rstrip() for s in x]
> 
> A quick test of 1,000,000 strings of length 27 took less than 0.2
> seconds on my PC.  Efficiency isn't really much of an issue for most
> data sets.



More information about the Python-list mailing list