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.
CodePudding user response:
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
CodePudding user response:
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!
