Print multiline strings side-by-side

前端 未结 4 587
长情又很酷
长情又很酷 2020-12-20 06:42

I want to print the items from a list on the same line. The code I have tried:

dice_art = [\"\"\"
 -------
|       |
|   N   |
|       |
 ------- \"\"\",\"\"         


        
相关标签:
4条回答
  • 2020-12-20 07:23

    Since the elements of dice_art are multiline strings, this is going to be harder than that.

    First, remove newlines from the beginning of each string and make sure all lines in ASCII art have the same length.

    Then try the following

    player = [0, 1, 2]
    lines = [dice_art[i].splitlines() for i in player]
    for l in zip(*lines):
        print(*l, sep='')
    

    If you apply the described changes to your ASCII art, the code will print

     -------  -------  ------- 
    |       ||       ||       |
    |   N   ||   1   ||   2   |
    |       ||       ||       |
     -------  -------  ------- 
    
    0 讨论(0)
  • 2020-12-20 07:23

    The fact that your boxes are multiline changes everything.

    Your intended output, as I understand it, is this:

     -------  -------
    |       ||       |
    |   N   ||   1   | ...and so on...
    |       ||       |
     -------  ------- 
    

    You can do this like so:

    art_split = [art.split("\n") for art in dice_art]
    zipped = zip(*art_split)
    
    for elems in zipped:
        print("".join(elems))
    #  -------  -------
    # |       ||       |
    # |   N   ||   1   |
    # |       ||       |
    #  -------  ------- 
    

    N.B. You need to guarantee that each line is the same length in your output. If the lines of hyphens are shorter than the other, your alignment will be off.

    In the future, if you provide the intended output, you can get much better responses.

    0 讨论(0)
  • 2020-12-20 07:24

    A join command should do it.

    dice_art = ['ASCII0', 'ASCII1', 'ASCII2']
    print(" ".join(dice_art))
    

    The output would be:

    ASCII0 ASCII1 ASCII2
    
    0 讨论(0)
  • 2020-12-20 07:41

    Change print(dice_art[i], end='') to:

    • print(dice_art[i], end=' '), (Notice the space inbetween the two 's and the , after your previous code)

    If you want to print the data dynamically, use the following syntax:

    • print(dice_art[i], sep=' ', end='', flush=True),
    0 讨论(0)
提交回复
热议问题