Slicing string into pieces with certain length in Python [duplicate]

I'm fairly new to Python and don't know how to do the following.

I want to 'cut' my string into pieces with a specific length and put these pieces into a list.

So when you have this:

'ATACAGGTA'

You need this list as the result:

['ATA', 'CAG', 'GTA']

It's probably pretty easy but I don't see how I can do this.


Solution 1:

s = 'ATACAGGTA'
step = 3
[s[i:i+step] for i in range(0, len(s), step)]

First define a string. Then the step size. Note that it is not checked if the step size fits in the length of the string.

Then a for loop is used to go over the string. The range function takes the start, stop and step argument (https://docs.python.org/3/library/functions.html#func-range). If you do not understand the list comprehension see: https://www.w3schools.com/python/python_lists_comprehension.asp