samedi 21 février 2015

Python - How to find if character is the last character in a string?

How do I efficiently check if a character when inside a for loop is in the last position of a string?


Like:



string = "daffyduck'd"


I would have done this through



for char in string:
if char == string[-1]:
break


This however prematurely ends whenever there is a char that matches the last element, so that does not work. I am dealing with pairs of chars, so when inside a for loop, i am doing a current_index and current_index + 1 operation, so without knowing the last element, I will get a string index out of bound error.


Aucun commentaire:

Enregistrer un commentaire