I have the following string
ACTGACTGACTGACTGACTGACTGACTGAC
And I want to display this string in lines of 10 character with each line seperated into groups of 5 character
So my first line would be:
ACTGA CTGAC
How to achieve this?
I have the following string
ACTGACTGACTGACTGACTGACTGACTGAC
And I want to display this string in lines of 10 character with each line seperated into groups of 5 character
So my first line would be:
ACTGA CTGAC
How to achieve this?
You can use the textwrap module to split your data in block of 10 characters, then format each line:
import textwrap
s = 'ACTGACTGACTGACTGACTGACTGACTGAC'
out = '\n'.join(line[:5] + ' ' + line[5:] for line in textwrap.wrap(s, 10))
print(out)
Output:
ACTGA CTGAC
TGACT GACTG
ACTGA CTGAC
The simple way is to use comprehensions, see example:
>>> the_string="ACTGACTGACTGACTGACTGACTGACTGAC"
>>> size_s=5
>>> var_buff = ''
>>> output=[the_string[var_buff-size_s:var_buff] for var_buff in range(size_s, len(the_string)+size_s,size_s)]
>>> print(output)
['ACTGA', 'CTGAC', 'TGACT', 'GACTG', 'ACTGA', 'CTGAC']
With this approach you can set the numbers of characters per line and per chunk:
s = 'ACTGACTGACTGACTGACTGACTGACTGAC'
m = 5 # chunk size
n = 10 # line size
tmp = [(s[i:i+m], s[i+m:i+n]) for i in range(0, len(s), n)]
for chunk1, chunk2 in tmp:
print(chunk1 + ' ' + chunk2)
Output:
ACTGA CTGAC
TGACT GACTG
ACTGA CTGAC
You could write your own generator function:
data = "ACTGACTGACTGACTGACTGACTGACTGAC"
def splitter(iterable, chunksize = 5):
buffer, idx = ['', 0]
for char in iterable:
idx += 1
buffer += char
if idx == chunksize:
buffer += " "
elif idx == (2 * chunksize):
yield buffer
buffer, idx = ['', 0]
# remaining part
if buffer:
yield buffer.rstrip()
for chunk in splitter(data):
print(chunk)
Which yields (but could be tweaked for other lengths as well)
ACTGA CTGAC
TGACT GACTG
ACTGA CTGAC
something like this should work. only for groups of five chars
string='ACTGACTGACTGACTGACTGACTGACTGAC'
string = list(string)
while string:
if len(string)>=10:
print(''.join(string[:5])+' '+''.join(string[5:10])+'\n')
string = string[10:]
else:
print(''.join(string[:5]))
string = string[5:]