Mahir Islam
Mahir Islam

Reputation: 1972

How to select certain pieces of a string in Python 3?

I am trying to select 2 letters from a string by using a sliding window. My code works but I am not getting the proper output. This is my code:

s = "aaabccddd"
b = [s[i:i + 2] for i in range(len(s) - 2)]
print(b)

The output from my code is:

['aa', 'aa', 'ab', 'bc', 'cc', 'cd', 'dd']

But the ouput should be like this:

['aa','ab','cc', 'dd', 'd']

How can i fix my code and get the desired ouput?

Upvotes: 0

Views: 55

Answers (1)

AntiMatterDynamite
AntiMatterDynamite

Reputation: 1512

you need to skip the right amount of bytes when you use range() like this: range(0, len(s) - 2, 2) , otherwise you would get two characters for every original character.

you can generalize this to any size of chunk you want:

def split_string(s, size):
    return [s[i:i+size] for i in range(0, len(s), size)]

Upvotes: 2

Related Questions