gpt4 book ai didi

python - 如何根据值分隔字符串

转载 作者:行者123 更新时间:2023-12-01 00:32:52 25 4
gpt4 key购买 nike

我试图将单个 print() 语句中的内容按指定的宽度隔开。我只发布相关代码:

def print_formatted(number):
# your code goes here
width = len(convert(number, 2))

for i in range(number):
print(
str(i + 1) + width +
str(convert(i + 1, 8)) + width +
str(convert(i + 1, 16)) + width +
str((convert(i + 1, 2)))
)

我知道串联 ...+ width + 不起作用。我把它放在那里是为了形象化我的目标是什么。我从文档中读到 format() 是可以使用的函数,但我还没有看到与我在这里尝试执行的类似的实现。

成功输出:

    1     1     1     1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001

最佳答案

您可以使用格式选项来实现此目的。不幸的是,您必须手动指定最大宽度,因为 print 无法知道稍后要打印的最大内容是什么:

list_of_tuples = list(zip(
range(10),
range(0, 20, 2),
range(0, 30, 3),
[10**i for i in range(10)]
))

width = 10 # Has to be specified manually, unfortuntately.
for tup in list_of_tuples:
print("\t".join(f"{number:>{width}}" for number in tup))

0 0 0 1
1 2 3 10
2 4 6 100
3 6 9 1000
4 8 12 10000
5 10 15 100000
6 12 18 1000000
7 14 21 10000000
8 16 24 100000000
9 18 27 1000000000

关于python - 如何根据值分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com