[Tutor] rstrip in list?

Steven D'Aprano steve at pearwood.info
Tue Feb 9 16:55:01 CET 2010

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.

Steven D'Aprano

More information about the Tutor mailing list