Search code examples
for-loopcharactercount

Count characters starting at zero?


I need to write a for-each loop that lists each character in mystery_string with its index. Example below:

mystery_string= "Olivia," output would be:

0 O
1 l
2 i
3 v
4 i
5 a

I cannot use the range function on this problem.
This is my code, but the number starts at 1. What am I doing wrong?

mystery_string = "CS1301"
count = 0 
for current_letter in mystery_string:
    count = count + 1
    print (count , current_letter)

I have been getting this as output:

1 C
2 S
3 1
4 3
5 0
6 1

but it needs to start at zero.


Solution

  • Just add the count (count += 1) after you print in the for loop

    Note: Also, please format your code in a code block surrounded with a tick(`) or multiline code with 3 tick (```)