简体   繁体   English

如何使用 python 中的字符串水平打印循环结果?

[英]How to print a loop's result horizontally with a string in python?

I want to print a loop's result horizontally with a string and a variable.我想用一个字符串和一个变量水平打印循环的结果。

My code我的代码

total = 0
for i in range(2, 6):
    total += i
    print(i, end=' ', 'sum = {}'.format(total))

The output I want:我要的output:

2 3 4 5 sum=14

You need to put the print of the sum outside the loop您需要将sum的打印放在循环之外

total = 0
for i in range(2, 6):
    total += i
    print(i, end=' ')
print('sum = {}'.format(total))

Output Output

2 3 4 5 sum = 14

Store the range then iterate and sum at the end存储范围然后迭代并在最后求和

r = range(2, 6)

for i in r:
    print(i, end=" ")

print(f"sum = {sum(r)}")

Store the range and format the string all on one line在一行中存储范围和格式化字符串

r = range(2, 6)

print(f'{" ".join([str(i) for i in r])} sum = {sum(r)}')

Add to the string in the loop then print at the end添加到循环中的字符串然后在最后打印

r = range(2, 6)

s = ""
for i in r:
    s += f"{i} "

print(f"{s}sum = {sum(r)}")

Aside from what Leo mentioned, you can also try to use f'{}' method to print.除了Leo提到的,您还可以尝试使用 f'{}' 方法进行打印。 I find it more handy and intuitive.我发现它更方便和直观。

total = 0
for i in range(2,6):
    total +=i
    print(i, ' ', end='')
print(f'sum={total}', end='')

Output: Output:

2  3  4  5  sum=14

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

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