gpt4 book ai didi

python - 如何摆脱打印语句中多余的 + 符号,Python

转载 作者:行者123 更新时间:2023-11-30 22:49:21 25 4
gpt4 key购买 nike

print('2**', n, ' + ', sep='', end='')

嗨,上面的 print 语句处于循环中,因此输出最终为

2 ** 10 + 2 ** 7 + 2 ** 6 + 2 ** 4 + 2 ** 1 +

我需要去掉语句中的最后一个加号,但不知道如何去做。

最佳答案

如果您将指数分开(正如您可能所做的那样),您可以使用 str.join() :

>>> exponents = (10, 7, 6, 4, 1)
>>> print(' + '.join('2**{}'.format(n) for n in exponents))
2**10 + 2**7 + 2**6 + 2**4 + 2**1

这适用于 Python 2 和 3。您还可以将 print() 函数与 sep 参数一起使用:

>>> print(*('2**{}'.format(n) for n in exponents), sep=' + ')
2**10 + 2**7 + 2**6 + 2**4 + 2**1

关于python - 如何摆脱打印语句中多余的 + 符号,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39829827/

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