如何在Python中打印并保持在同一行
我想知道怎么把两个东西打印在同一行,而不是换行。
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?:
那么,我该怎么把它们放在同一行呢?
2 个回答
2
在Python 3中:
print('Some stuff', end='')
在Python 2中:
print 'Some stuff',
5
python2:
print "hello",
print "there"
注意最后的逗号。在打印语句后面加一个逗号,可以抑制换行符的效果。还要注意,我们在“hello”后面没有加空格——打印时的最后逗号也会在字符串后面加一个空格。
即使在有多个字符串的复合语句中,这个方法也能用:
python2:print "hello", "there", "henry",
print "!"
打印结果是:
hello there henry !
在python3中:
print("hello ", end=' ')
print("there", end='')
打印函数的默认结束参数是'\n',也就是换行符。所以在python3中,你需要自己指定结束符为空字符串,才能抑制换行符的效果。
注意:你可以使用任何字符串作为结束符:
print("hello", end='LOL')
print("there", end='')
打印结果是:
helloLOLthere
比如,你可以设置end=' ',这样就可以避免在打印字符串的末尾加空格。这非常实用 :)
print("hello", end=' ')
print("there", end='')