Getting every nth character in the string in Python

Viewed 20691

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   
5 Answers

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'

If somebody asked me to give every nth character in a string, I wouldn't include the first character. I would rather do something like below:

def GetNthLetters(text, n):
    builtstring = ""
    for i in range(0, len(text)):
        if (i + 1) % n == 0:
            # print(text[i])
            builtstring = builtstring + text[i]
    return builtstring


text = '1234567890123456789012345678901234567890'

nthLetters = GetNthLetters(text, 1)
print(nthLetters)
nthLetters = GetNthLetters(text, 2)
print(nthLetters)
nthLetters = GetNthLetters(text, 3)
print(nthLetters)
nthLetters = GetNthLetters(text, 10)
print(nthLetters)
nthLetters = GetNthLetters(text, 40)
print(nthLetters)

This would yield these results:

1234567890123456789012345678901234567890

24680246802468024680

3692581470369

0000

0

string = "12345678"

n = 2

splitted_string = string[::n]

print(splitted_string)

# Output : 1357

Hope this will help.!

Using Python's slicing syntax:

Python's slicing syntax is much like the range() function. It accepts a start, stop and step value:

string[start : stop : step]

where you can leave any of the parameters blank and they will default to 0, the length of the string and 1 respectively.

This means you can do:

string[::n]

to get a string's every nth characterter.

So you can write the function as:

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

Hope this does what you want!

The problem with the code is everytime the index of same repeated letter will give same result.

For example 'Hello World!'.index('o') will be always 4 so it will not give intended result.

The best way is to enumerate the for loop. so you will get appropriate index.

You should also remember array starts with 0 not 1.

Related