slicing the end of a string in a list
Ben Cartwright
bencvt at gmail.com
Thu Mar 2 22:37:32 EST 2006
John Salerno wrote:
> You can probably tell what I'm doing. Read a list of lines from a file,
> and then I want to slice off the '\n' character from each line. But
> after this code runs, the \n is still there. I thought it might have
> something to do with the fact that strings are immutable, but a test
> such as:
>
> switches[0][:-1]
>
> does slice off the \n character.
Actually, it creates a new string instance with the \n character
removed, then discards it. The original switches[0] string hasn't
changed.
>>> foo = 'Hello world!'
>>> foo[:-1]
'Hello world'
>>> foo
'Hello world!'
> So I guess the problem lies in the
> assignment or somewhere in there.
Yes. You are repeated assigning a new string instance to "line", which
is then never referenced again. If you want to update the switches
list, then instead of assigning to "line" inside the loop, you need:
switches[i] = switches[i][:-1]
> Also, is this the best way to index the list?
No, since the line variable is unused. This:
i = 0
for line in switches:
line = switches[i][:-1]
i += 1
Would be better written as:
for i in range(len(switches)):
switches[i] = switches[i][:-1]
For most looping scenarios in Python, you shouldn't have to manually
increment a counter variable.
--Ben
PS - actually, you can accomplish all of the above in a single line of
code:
print [line[:-1] for line in open('C:\\switches.txt')]
More information about the Python-list
mailing list