Home > Blockchain >  Shortest code to return current index number in string in 'for n in 'word': loop
Shortest code to return current index number in string in 'for n in 'word': loop

Time:12-16

I have a question about strings. I thought that this code:

for n in 'banana':
    print(n)

would return this:

0 1 2 3 4 5

But, of course, it doesn't. It returns the value at each position in the string, not the position number. In order for me to understand this better, I thought it might help to write the simplest possible program to achieve the output I thought I'd get:

count = 0
for n in 'banana':
    print(count)
    count  = 1

This works, but surely there's a more direct way to access the position number that the current iteration is looking at? Can't see any methods that would achieve this directly though.

CodePudding user response:

These are all equivalent:

i = 0
for n in 'banana':
    print(i)
    i  = 1
for i, w in enumerate('banana'):
    print(i)
for i in range(len('banana')):
    print(i)
print(*range(len('banana')), sep='\n')

CodePudding user response:

As posted in the other answer, enumerate() works:

for idx, character in enumerate('myword'):
    print(f"Index={idx} character={character}")

It is worth pointing out that in this Python treats strings as arrays. When you have "abc"[0] it will return a. And, similarly, when you say 'give me each element in some array' it will simply give you the element, not the index of that element - which would be counterintuitive.

  • Related