-2

I was given this problem in a Python class I'm taking. Take a string as input and output each letter of the string on a new line, repeated N times, where N is the position of the letter in the string.

Here is my first attempt:

string = input()

for i in string:
    n = string.index(i) + 1
    print(i * n)

'''

but the output for the input: 'awesome', was:

'''

a
ww
eee
ssss
ooooo
mmmmmm
eee

'''

The output I want is:

'''

a
ww
eee
ssss
ooooo
mmmmmm
eeeeeee

'''

I was able to figure out a different way of doing it, that ended up giving me the correct output:

string = input()
i = 0
while i < len(string):
    
    print(string[i] * (i + 1))
    i += 1

a
ww
eee
ssss
ooooo
mmmmmm
eeeeeee

My question now is why my first attempt does not give me the expected output.

  • 2
    If you want the index in a for loop, use `for index, elem in enumerate(sequence)` – Pranav Hosangadi Feb 16 '22 at 18:22
  • 1
    *"My question now is why my first attempt does not give me the expected output"* - the answer is in [the docs](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations) - *"index of __the first__ occurrence of x in s"* – Tomerikoo Feb 16 '22 at 18:29
  • Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Tomerikoo Feb 16 '22 at 18:30

1 Answers1

2

string.index(i) returns the first index of i, which is simply the letter e in this case (when you call string.index('e'), Python doesn't know you've obtained 'e' as the x'th letter from the same string).

Orius
  • 1,093
  • 5
  • 11