如何在Python中打印并将它们放在同一行中

rZe*_*ro3 0 python newline

如何在一行中打印两个内容,使其不在新行中

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?")
Run Code Online (Sandbox Code Playgroud)

当我运行它

alright 
How are you?: 
Run Code Online (Sandbox Code Playgroud)

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

Pod*_*Pod 5

python2:

print "hello",
print "there"
Run Code Online (Sandbox Code Playgroud)

注意尾随的逗号.print语句后面的尾随逗号会抑制换行符.另请注意,我们不在hello的末尾添加空格 - 用于print的尾随逗号也会在字符串后面放置一个空格.

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

print "hello", "there", "henry",
print "!"
Run Code Online (Sandbox Code Playgroud)

打印:

hello there henry !
Run Code Online (Sandbox Code Playgroud)

在python3中:

print("hello ", end=' ')
print("there", end='')
Run Code Online (Sandbox Code Playgroud)

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

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

print("hello", end='LOL')
print("there", end='')
Run Code Online (Sandbox Code Playgroud)

打印:

helloLOLthere
Run Code Online (Sandbox Code Playgroud)

例如,您可以使用end =''来避免在打印字符串的末尾添加空格.那非常有用:)

print("hello", end=' ')
print("there", end='')
Run Code Online (Sandbox Code Playgroud)