答复: 答复: how to remove \n in the list

Penny Y. pylists at arcor.de
Mon Apr 14 10:37:16 CEST 2008


that's right. got it thanks. 

-----邮件原件-----
发件人: python-list-bounces+pylists=arcor.de at python.org
[mailto:python-list-bounces+pylists=arcor.de at python.org] 代表 Eric Brunel
发送时间: 2008年4月14日 16:17
收件人: python-list at python.org
主题: Re: 答复: how to remove \n in the list

(please avoid top-posting... corrected)
On Mon, 14 Apr 2008 09:08:06 +0200, Penny Y. <pylists at arcor.de> wrote:
> -----邮件原件-----
> 发件人: python-list-bounces+pylists=arcor.de at python.org
> [mailto:python-list-bounces+pylists=arcor.de at python.org] 代表 Gabriel
> Genellina
> 发送时间: 2008年4月14日 12:59
> 收件人: python-list at python.org
> 主题: Re: how to remove \n in the list
>
> En Mon, 14 Apr 2008 01:41:55 -0300, reetesh nigam
> <nigamreetesh84 at gmail.com> escribió:
>
>> hi,
>> l=['5\n', '2\n', '7\n', '3\n', '6\n']
>>
>> how to remove \n from the given list
>
> l is is very poor name... I'll use lines instead:
>
> lines[:] = [line.rstrip('\n') for line in lines]
> ---
>
> why not just:
>
> lines = [line.rstrip('\n') for line in lines]
>
>
> what's the difference between lines[:] and lines here? Thanks.

Compare:

>>> lines = ['5\n', '2\n', '7\n', '3\n', '6\n']
>>> lines2 = lines
>>> lines = [line.rstrip('\n') for line in lines]
>>> lines
['5', '2', '7', '3', '6']
>>> lines2
['5\n', '2\n', '7\n', '3\n', '6\n']

with:

>>> lines = ['5\n', '2\n', '7\n', '3\n', '6\n']
>>> lines2 = lines
>>> lines[:] = [line.rstrip('\n') for line in lines]
>>> lines
['5', '2', '7', '3', '6']
>>> lines2
['5', '2', '7', '3', '6']

Assigning to lines[:] changes the original list. Assigning to lines  
rebinds the name to the result of the list comprehension, but doesn't  
affect the original list.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list