简体   繁体   English

并排打印多行字符串

[英]Print multiline strings side-by-side

I want to print the items from a list on the same line. 我想在同一行上打印列表中的项目。 The code I have tried: 我尝试过的代码:

dice_art = ["""
 -------
|       |
|   N   |
|       |
 ------- ""","""
 -------
|       |
|   1   |
|       |
 ------- """] etc...

player = [0, 1, 2]
for i in player:
    print(dice_art[i], end='')

output = 输出=

ASCII0
ASCII1
ASCII2

I want output to = 我想输出到=

ASCII0 ASCII1 ASCII2

This code still prints the ASCII art representation of my die on a new line. 此代码仍在新行上打印我的模具的ASCII艺术表现形式。 I would like to print it on the same line to save space and show each player's roll on one screen. 我想将其打印在同一行上,以节省空间并在一个屏幕上显示每个玩家的状态。

Since the elements of dice_art are multiline strings, this is going to be harder than that. 由于dice_art的元素是多行字符串,因此将比这更难。

First, remove newlines from the beginning of each string and make sure all lines in ASCII art have the same length. 首先,从每个字符串的开头删除换行符,并确保ASCII插图中的所有行都具有相同的长度。

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 如果您将描述的更改应用于ASCII艺术作品,则将打印代码

 -------  -------  ------- 
|       ||       ||       |
|   N   ||   1   ||   2   |
|       ||       ||       |
 -------  -------  ------- 

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   |
# |       ||       |
#  -------  ------- 

NB 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. 将来,如果您提供预期的输出,则可以获得更好的响应。

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

  • print(dice_art[i], end=' '), (Notice the space inbetween the two ' s and the , after your previous code) print(dice_art[i], end=' '),注意其间的两个空间' S和,以前的代码之后)

If you want to print the data dynamically, use the following syntax: 如果要动态打印数据,请使用以下语法:

  • print(dice_art[i], sep=' ', end='', flush=True),

A join command should do it. 连接命令应该执行此操作。

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

The output would be: 输出为:

ASCII0 ASCII1 ASCII2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM