Count characters starting at zero?

92 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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 (```)

0
On

The pythonic way is to use enumerate() in such a case. This way you'll get both the index and the content of your string.

mystery_string = "CS1301"
for count, current_letter in enumerate(mystery_string):
    print (count , current_letter)