[英]Python print horizontally on multiple lines at once
end=" "
argument to the print
function did not work, and neither did anything else I found on stackoverflow.end=" "
print
function 的参数没有用,我在 stackoverflow 上发现的其他任何东西也没有用。 In its current state it prints vertically, down the command prompt, which is not what I want.string = "hello world"
for ch in string:
print(f'''
{ch}
{ord(ch)}
''')
h e l l o w o r l d
104 101 108 108 111 32 119 111 114 108 100
Actual Output:实际 Output:
h
104
e
101
... ... trimmed for brevity ... ...
l
108
d
100
One approach could be to build out the ord
values using a list
comprehension, and then iterate over each char and ord pair in the string
, and then print out each char padded to the string length of each ord
- ie a numeric value of 102
would mean a pad width of 3.一种方法是使用
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)
Result:结果:
h e l l o w o r l d
104 101 108 108 111 32 119 111 114 108 100
If you need to split this off into chunks, for example if your string is too long and you need it to fit your terminal or window, you can use an approach as mentioned here in order to split the string into chunks, and still keep the same logic above.如果您需要将其拆分成块,例如,如果您的字符串太长并且您需要它适合您的终端或 window,您可以使用此处提到的方法将字符串拆分成块,并仍然保留同上逻辑。
Here's an example of how that could work.这是一个如何工作的例子。 Note that you'll need to adjust
chunk_size
based on width of your terminal 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: 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.