In C, as well as in C++, one can in a for-loop change the index (for example i
). This can be useful to, for example, compare a current element and based on that comparison compare the next element:
for(int i = 0; i < end; i++)
if(array[i] == ':')
if(array[++i] == ')')
smileyDetected = true;
Now I know this cannot be done in Python (for various reasons). However, I cannot help wondering if there are short alternatives for Python? I can come up with:
while i < end:
if array[i] == ':':
i += 1
if array[i] == ')':
smileyDetected = True;
However, this costs me an extra line, which doesn't sound so bad until you do the same multiple times ('less readable' did not mean having a long file). So to have it in one line, I would think of something like
array[i += 1]
, but this is invalid syntax as it seems.
Is there Python equivalent which does the incrementation of the index in the same line as reading out that incremented index?
EDIT:
As most answers mention using in
to find a substring, as an alternative for the particular example, let me add another example which wouldn't be solvable in such a way:
j = 0;
for(int i = 0; i < end; i++)
if(array[i] == ':')
if(array[++i] == ')')
anotherArray[j++] = array[++i];
With that I mean it's about the incrementing of the index, not the finding of a particular string.