Reputation: 151
I'm learning Python and for some reason I have a strange problem with negative indexes. Instead of getting the last character I get an empty string. And instead of getting all character but last I get the whole string back. Here is the code I'm using:
print('Starting loop')
for line in sys.stdin:
last = line[-1]
print 'last = ' + last
allButLast = line[:-1]
print 'AllButLast = ' + allButLast
The result:
Starting loop
123
123
last =
AllButLast = 123
last =
AllButLast = 123
Upvotes: 2
Views: 291
Reputation: 13934
Add line = line.rstrip()
at the beginning of the for
loop to get desired value. Currently newline is being captured as line[-1]
, so you need to remove that first. The enter that you press just after typing 123
is nothing but a newline.
Upvotes: 4