0

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?

Jan
  • 42,290
  • 8
  • 54
  • 79
ptalebic
  • 47
  • 7
  • 5
    What you have tried so far, please show us your efforts. – Debendra Nov 03 '19 at 18:48
  • 1
    Possible duplicate of [What's the best way to split a string into fixed length chunks and work with them in Python?](https://stackoverflow.com/questions/18854620/whats-the-best-way-to-split-a-string-into-fixed-length-chunks-and-work-with-the) – musicamante Nov 03 '19 at 18:50

5 Answers5

3

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
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

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']
0

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
AnsFourtyTwo
  • 2,480
  • 2
  • 13
  • 33
0

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
Jan
  • 42,290
  • 8
  • 54
  • 79
0

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:]