Kevin
Kevin

Reputation: 6833

How to print several strings side-by-side and span multiple lines at a fixed output width

I am trying to print out three long strings (same-length), character-by-character, and with a fixed output width at 60, which may be rendered like:

aaaaaaaaaaaaa
bbbbbbbbbbbbb
ccccccccccccc
---blank line---
aaaaaaaaaaaaa
bbbbbbbbbbbbb
ccccccccccccc

.....

I simplify the strings so that the first string is an arbitrarily long string contains "a"s, the second string contains many "b"s, etc. There could be as many blocks of lines shown above as possible, within each block, the first line stands for string1, second line stands for string2..etc. .And since a fixed output width is required, the printing will continue at the next block of three lines(for example, str1 will continue at the first line of the second block if length>60).

My current code looks like:

 for chunk in chunkstring(str1, 60):
    f.write(chunk)
    f.write('\n')
 for chunk in chunkstring(str2, 60):
    f.write(chunk)
    f.write('\n')
 for chunk in chunkstring(str3, 60):
    f.write(chunk)
    f.write('\n')

However, the result is not correct. It will print out all the str1 first then str2, then str3

  aaaaaaaaaaaaa
  aaaaaaaaaaaaa
  aaaaaaaaaaaaa
  aaaa
  ---blank line---
  bbbbbbbbbbbbb
  bbbbbbbbbbbbb
  bbbbbb
  ---blank line---
  ccccccccccccc
  cccc
  .....

Sorry if not intepretted clearly, please highlight any ambiguation so I can edit the descrption.

Upvotes: 2

Views: 67

Answers (2)

Alain T.
Alain T.

Reputation: 42143

You could push Pranav's zip approach even further and use zip for the chunking as well:

s1 = "a"*180
s2 = "b"*180
s3 = "c"*180

def chunk60(s): return map("".join,zip(*[iter(s)]*60))
for lines in zip(*map(chunk60,(s1,s2,s3))):
    print(*lines,sep='\n')
    print("...")

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
...
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
...
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
...

Upvotes: 1

pho
pho

Reputation: 25489

You will need to chunk all strings, and then iterate over the chunks simultaneously using zip. Now, block is a tuple containing the individual chunks of each string

chunks = [chunkstring(s, 60) for s in (str1, str2, str3)]

for block in zip(*chunks):
    for c in block:
        # write all lines in block
        f.write(c)
        f.write('\n')
    # at the end of the block, write a blank line 
    f.write('\n')

Try it online

Upvotes: 2

Related Questions