Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get the last index number
#1
s = "kitti"

0,1,2,3,4
k,i,t,t,i
how do i retrieve '4', the last index value. i know i can do a len(s)-1, but i assume there is a function that gives me last number of index, or more eloquent way. Maybe not, just checking

thanks
Reply
#2
>>> s = 'kitti'
>>> idx = len(s) -1
>>> s[idx]
'i'
>>> s[-1]
'i'
>>> s[len(s)-1]
'i'
>>> len(s)-1
4
>>>
Reply
#3
I can think of couple of solutions

def last_index(string_, char):
   index = -1
   for pos, c in enumerate(string_):
       if c == char:
          index = pos
   return index

def last_index_short(string_, char):
    return length(string_) - string_[::-1].index(char) - 1
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
>>> s = 'kitty'
>>> s.rindex(s[-1])
4
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Find index of missing number parthi1705 3 3,144 May-07-2019, 10:52 AM
Last Post: avorane

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020