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.
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.
If all you want to do is to process two neighboring characters at a time, then don't use the index, and simply zip
the actual string with the same string without the first character, like this
>>> input_string = "daffyduck'd"
>>> for char1, char2 in zip(input_string, input_string[1:]):
... print(char1, char2)
...
...
d a
a f
f f
f y
y d
d u
u c
c k
k '
' d
Note: Your original approach also has a problem, what if the last character occurs somewhere in the middle of the string? This condition will make the loop break immediately
if char == string[-1]:
Instead, use enumerate
function, like this
for index, char in enumerate(input_string):
if index + 1 == len(input_string):
break
enumerate
will give the current index and the actual item from the iterable, on every iteration. So, you can check if the current index + 1 is equal to the length of the string to make sure that you are really at the last position of the string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.