Cem Aytekin Cem Aytekin - 3 years ago 128
Python Question

Getting every nth character in the string in Python

I have the following function but it doesn't give me the intended result:

def GetNthLetters(text,n):
builtstring=""
for letter in text:
if text.index(letter)%n==0:
builtstring=builtstring+letter
print letter
return builtstring

Answer Source

str.index() finds the first match for your letter. If you have a letter that appears more than once, that'll give you the wrong index. For any given character, you only test if their first occurrence in the string is at a n'th position.

To demonstrate, take a look at the string 'hello world' with the character indices (I used . to mark the space):

0 1 2 3 4 5 6 7 8 9 10
h e l l o . w o r l d

For the letter l, text.index('l') will return 2, so it'll only be included in the output if n is 1 or 2. It doesn't matter that l also appears at index 3 or 9, because you only ever test 2 % n == 0. The same applies for 'o' (positions 4 and 7), only 4 % n == 0 is tested for either.

You could use the enumerate() function to give you a running index:

def GetNthLetters(text, n):
    builtstring = ""
    for index, letter in enumerate(text):
        if index % n == 0:
            builtstring = builtstring + letter
    return builtstring

Now index is correct for every letter, repeated or not.

However, it'll be much easier to use slicing:

def GetNthLetters(text, n):
    return text[::n]

This takes every n'th letter too:

>>> 'foo bar baz'[::2]
'fobrbz'
>>> 'foo bar baz'[::3]
'f ra'
>>> 'foo bar baz'[::4]
'fbb'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download