Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 - last character of the string [duplicate]

I want to get the last character of the string. I can print it using len method to get it BUT I can't compare it to another character while getting it using the VERY SAME method. Now I'll just paste this WTF code here. Please tell me what's going on here.

fields = line.split(';')
last = fields[0]
capacity = fields[1]
region = fields[2]

print(capacity)
print('kek')
print(capacity[len(capacity)-1])
print('even more kek')
while capacity[len(capacity)-1] == '0':
    capacity = capacity[1:len(capacity)-2]
    last = last[1:len(last)-2]

Now, the output

100000
kek
0
even more kek
Traceback (most recent call last):
  File "/home/mekkanizer/Документы/proj/rossvyaz/making_insert_queries.py", line 52, in <module>
    while capacity[len(capacity)-1] == '0':
IndexError: string index out of range
like image 304
mekkanizer Avatar asked Sep 08 '25 07:09

mekkanizer


2 Answers

You ended up with an empty string, so there is nothing to index anymore:

>>> ''[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

You do so by shortening capacity in the while loop:

capacity = capacity[1:len(capacity)-2]

You start with 100000, then make that '000', then '':

>>> capacity = '100000'
>>> capacity[1:len(capacity)-2]
'000'
>>> capacity[1:len(capacity)-2][1:len(capacity)-2]
''

You may have missed you are doing this as you are never printing the value of capacity in the loop.

You can always index from the end using negative indices:

>>> 'last character'[-1]
'r'

This works for slicing too:

>>> 'last character'[5:-4]
'chara'
like image 55
Martijn Pieters Avatar answered Sep 10 '25 07:09

Martijn Pieters


You can use slicing notation which will return "" for an empty string:

while capacity[len(capacity)-1:] == 0

Or use while capacity to catch empty strings:

while capacity and capacity[-1] == "0":

You keep shortening capacity when reassigning capacity in your while loop so eventually it will be an empty string:

 capacity = capacity[1:len(capacity)-2] 

foobar foobar <- start
oobar foob <- first iteration
obar fo <- second iteration
bar  <- third iterations
a <- fourth iteration
empty string == index error
like image 37
Padraic Cunningham Avatar answered Sep 10 '25 09:09

Padraic Cunningham