[Tutor] rstrip in list? (SOLVED)
Ken G.
beachkid at insightbb.com
Tue Feb 9 18:14:54 CET 2010
There was so many different solutions presented here to me.
Thanks to all. By adding '.strip('\n') to the last two lines below, it
came out:
Sorted List
['102', '231', '463', '487', '555', '961']
for line in file.readlines():
print line.strip('\n'),
mylist.append(line.strip('\n'))
Further work and studying needed here. LOL.
Ken
Steven D'Aprano wrote:
> On Wed, 10 Feb 2010 02:28:43 am Ken G. wrote:
>
>> I printed out some random numbers to a list and use 'print mylist'
>> and they came out like this:
>>
>> ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n']
>>
>> I was using 'print mylist.rstrip()' to strip off the '\n'
>>
>> but kept getting an error of :
>>
>> AttributeError: 'list' object has no attribute 'rstrip'
>>
>
> You have to apply rstrip to each item in the list, not the list itself.
>
> Here are two ways to do it:
>
> #1: modify the list in a for-loop
> for i, item in enumerate(mylist):
> mylist[i] = item.rstrip()
>
> #2: make a new list with a list comprehension
> mylist = [item.rstrip() for item in mylist]
>
>
> Of the two, I prefer the second.
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100209/fe6f711a/attachment-0001.htm>
More information about the Tutor
mailing list