0

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.

1

2 Answers 2

2
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

0
0

Taken from here:

https://www.kite.com/python/answers/how-to-split-a-string-at-every-nth-character-in-python

modfied for your case, should do the trick:

a_string = "ATACAGGTA"

split_strings = []
n  = 3
for index in range(0, len(a_string), n):
    split_strings.append(a_string[index : index + n])

print(split_strings)

Output:

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

It may be that there is a more "pythonic" way!

Cheers!

1
  • There is. You can do it all in 1 line with a list comprehension.
    – MattDMo
    Commented Jan 11, 2022 at 15:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.