[Tutor] For loop breaking string methods
Sander Sweers
sander.sweers at gmail.com
Mon Apr 26 22:59:15 CEST 2010
On 26 April 2010 21:38, C M Caine <cmcaine at googlemail.com> wrote:
> Why does this not work:
>>>> L = [' foo ','bar ']
>>>> for i in L:
> i = i.strip()
str.strip() _returns_ a *new* string and leaves the original string
alone. The reason being that string are immutable so can not be
changed.
>>> s1 = ' foo '
>>> s1[1]
'f'
>>> s1[1] = 'g'
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
s1[1] = 'g'
TypeError: 'str' object does not support item assignment
However lists are mutable and can be changed in place.
>>> l = [' foo ','bar ']
>>> l[0] = ' boo '
>>> l
[' boo ', 'bar ']
>>> l[1] = 'far '
>>> l
[' boo ', 'far ']
> But this does:
>>>> L = [i.strip() for i in L]
>>>> L
> ['foo', 'bar']
What you do here is create a *new* list object and assign it to
variable L. The new list is created with *new* string objects returned
by str.strip().
Putting the 2 together you could do something like below but I would
use a list comprehension like you did above:
>>> l = [' foo ','bar ']
>>> for x in range(len(l)):
l[x] = l[x].strip()
>>> l
['foo', 'bar']
>>>
> What other strange behaviour should I expect from for loops?
You should read up on immutable data types like strings and tuples.
Start with [1].
Greets
Sander
[1] http://docs.python.org/reference/datamodel.html
More information about the Tutor
mailing list