不知道如何在 python 中水平打印? [英] Can't figure out how to print horizontally in python?

查看:61
本文介绍了不知道如何在 python 中水平打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打印此代码:

 for x in range (1, 21):如果 x%15==0:打印(嘶嘶声")elif x%5==0:打印(嗡嗡声")elif x%3==0:打印(嘶嘶声")别的:打印 (x)

水平而不是垂直打印,就像这样:

<前>123

<前>1 2 3

我不知道该怎么做,一些帮助会很棒.谢谢

解决方案

两个选项:

累积一个结果字符串并print最后:

result = ""对于范围 (1, 21) 中的 x:如果 x%15==0:结果=结果+嘶嘶声"等等...打印结果

或者告诉 Python 不要以换行符结束打印的字符串.在您似乎正在使用的 Python 3 中,您可以通过设置 print 函数的 end 参数来实现,即 "\n"(换行)默认:

 for x in range (1, 21):如果 x%15==0:打印(嘶嘶声",结束=")等等...

历史注释:在 Python 2 中,这可以通过在 print 语句的末尾添加逗号来实现;打印fizzbuzz",

I need to print this code:

for x in range (1, 21):  

    if x%15==0:
        print("fizzbuzz")

    elif x%5==0:
        print("buzz") 
    elif x%3==0:
        print("fizz")

    else:
        print (x)

Horizontally instead of it printing vertically, like this:

1

2

3

to

1 2 3

I am not sure how to, some help would be great. Thanks

解决方案

Two options:

Accumulate a result string and print that at the end:

result = ""  
for x in range (1, 21):  

    if x%15==0:
        result = result + "fizzbuzz "

    etc...
print result

Or tell Python not to end the printed string with a newline character. In Python 3, which you seem to be using, you do this by setting the end argument of the print function, which is "\n" (a newline) by default:

for x in range (1, 21):  

    if x%15==0:
        print("fizzbuzz",end=" ")

    etc...

Historical note: In Python 2, this could be achieved by adding a comma at the end of the print statement; print "fizzbuzz",

这篇关于不知道如何在 python 中水平打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆