The Rabid Camel
The Rabid Camel

Reputation: 21

(Python) First letter of string printing twice

I am trying to put every letter that has an index of % 12 = 0 into a separate string. But for some reason it keeps printing the first letter of the string twice? FYI: the code is really basic, I'm not great at coding but trying to get better. Thanks.

string1 = 'nfhcizhfpntxolaqhpgvjehzsw'

final = ' '

for letter in string1:
    if (string1.index(letter) % 12 == 0):
        final = final + letter
        print (letter)

It outputs the following: nnos

When it should be: nos

Upvotes: 2

Views: 349

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

index returns the first occurrence of the letter in the string.

Since n is present at first position (it works) but also at another position, the second call also returns 0 and the letter is duplicated (it also has a nasty O(n**2) complexity because it searches from the beginning every time, even when it works)

The proper way is:

string1[::12]

slices the string to take each 12th character starting from index 0. Also avoids the ugly and underperformant string concatenation

Upvotes: 8

Related Questions