繁体   English   中英

Python 一次在多行上水平打印

[英]Python print horizontally on multiple lines at once

  • 我正在尝试在其正下方打印字符串及其相应的十进制 ascii 值。 这似乎是一项简单的任务,但经过大量研究后,我还没有找到解决问题的方法。 使用end=" " print function 的参数没有用,我在 stackoverflow 上发现的其他任何东西也没有用。 在当前的 state 中,它在命令提示符下垂直打印,这不是我想要的。 我需要它水平打印。
string = "hello world"
for ch in string:
  print(f'''
        {ch}
        {ord(ch)}
        ''')
  • 所需 Output:
h   e   l   l   o        w   o   r   l   d
104 101 108 108 111  32  119 111 114 108 100 

实际 Output:

h
104

e
101

... ... trimmed for brevity ... ...

l
108

d
100
  • 我知道一路上的某个地方我不得不担心顶线的宽度小于底线的宽度,这样字符才能很好地匹配,但假设我现在不担心这个。

一种方法是使用list理解构建ord值,然后遍历string中的每个 char 和 ord 对,然后打印出填充到每个ord的字符串长度的每个 char - 即102的数值意味着焊盘宽度为 3。

string = "hello world"
ords = [ord(ch) for ch in string]

for ch, ord_ in zip(string, ords):
    len_ord = len(str(ord_))
    print(ch.ljust(len_ord), end=' ')

print()
print(*ords)

结果:

h   e   l   l   o      w   o   r   l   d   
104 101 108 108 111 32 119 111 114 108 100

如果您需要将其拆分成块,例如,如果您的字符串太长并且您需要它适合您的终端或 window,您可以使用此处提到的方法将字符串拆分成块,并仍然保留同上逻辑。

这是一个如何工作的例子。 请注意,您需要根据终端 window 的宽度调整chunk_size

string = "hello world, how is it going there?"
ords = [ord(ch) for ch in string]

# TODO: can set this based on your terminal width
chunk_size = 10

for i in range(0, len(string), chunk_size):
    ords_chunk = ords[i:i + chunk_size]
    for ch, ord_ in zip(string[i:i + chunk_size], ords_chunk):
        len_ord = len(str(ord_))
        print(ch.ljust(len_ord), end=' ')
    print()
    print(*ords_chunk)

Output:

h   e   l   l   o      w   o   r   l   
104 101 108 108 111 32 119 111 114 108
d   ,     h   o   w      i   s      
100 44 32 104 111 119 32 105 115 32
i   t      g   o   i   n   g      t   
105 116 32 103 111 105 110 103 32 116
h   e   r   e   ?  
104 101 114 101 63

暂无
暂无

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

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