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.

HitZa
  • 21
  • 1
  • 2
    What have you tried? Have you searched for a similar question before asking? Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. Also [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953) Welcome to Stack Overflow! – Pranav Hosangadi Jan 11 '22 at 14:54

2 Answers2

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

3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
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!