【问题标题】:How to print things and put them in the same line in Python [duplicate]如何打印东西并将它们放在Python中的同一行[重复]
【发布时间】:2014-04-30 08:50:16
【问题描述】:

如何在一行中打印两个东西,这样它就不会在新行中了

print ("alright " + name)
howareyou = input("How are you?: ")

if howareyou == "good" or "Good" or "Alright" or "GOOD" or "bad" or "BAD":
    print ("Alright")
else:
    print ("What is that?")

当我运行它时

alright 
How are you?: 

那么,如何将它们放在同一行?

【问题讨论】:

  • 另外:stackoverflow.com/q/4390942/748858(对于 python2.x)
  • 附带说明,您错误地使用了or 运算符。参考here
  • 好的,谢谢大家,但我明白了:howareyou = input("Alright " + name + " how are you?: ")

标签: python newline


【解决方案1】:

python2:

print "hello",
print "there"

注意结尾的逗号。打印语句后的尾随逗号抑制换行符。另请注意,我们不会在 hello 的末尾放置一个空格 - 用于打印的尾随逗号也会在字符串之后放置一个空格。

它甚至在具有多个字符串的复合语句中也有效: python2:

print "hello", "there", "henry",
print "!"

打印:

hello there henry !

在python3中:

print("hello ", end=' ')
print("there", end='')

打印函数的end参数默认值为'\n',即换行符。因此,在 python3 中,您可以通过将结束字符指定为空字符串来自己抑制换行符。

注意:您可以使用任何字符串作为结束符号:

print("hello", end='LOL')
print("there", end='')

打印:

helloLOLthere

例如,您可以设置 end=' ' 以避免在打印字符串的末尾添加空格。这非常有用:)

print("hello", end=' ')
print("there", end='')

【讨论】:

  • 谢谢,真的很有帮助
  • 并且,为了完成这个,为了符合python2.6+,你可以使用带有from __future__ import print_function的python3版本
【解决方案2】:

在 Python 3 中:

print('Some stuff', end='')

在 Python 2 中:

print 'Some stuff',

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多