简体   繁体   中英

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?

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM