在 Python 3.2.3 中的一行中执行多个语句

在 Python 3.2.3 中的一行中执行多个语句

有没有办法在一行中执行多个语句,如下所示:

import time
print ("Ok, I know how to write programs in Python now.")
time.sleep(0.5)
print (".") # This should print on the same line as the previous print statement.
time.sleep(0.5)
print (".") # ... As should this one

...因此输出应该是:

Ok, I know how to write programs in Python now.*.*.

*等待.5秒

答案1

在 Python 2 中,该print语句会自动添加换行符,因此您需要改用 sys.stdout.write()。您还必须导入 sys。您编写的代码应如下所示:

import time
import sys
sys.stdout.write("Ok, I know how to write programs in Python now.")
time.sleep(0.5)
sys.stdout.write(".")
time.sleep(0.5)
sys.stdout.write(".")

在 Python 3 中,print是一个接受关键字参数的函数。您可以使用end关键字参数来指定字符串后面应放置的内容。默认情况下,它是一个换行符,但您可以将其更改为空字符串:

import time
print("Ok, I know how to write programs in Python now.", end='')
time.sleep(0.5)
print(".", end='')
time.sleep(0.5)
print(".", end='')

另外,请记住流是缓冲的,因此最好刷新它们:

import time
import sys
print("Ok, I know how to write programs in Python now.", end='')
sys.stdout.flush()
time.sleep(0.5)
print(".", end='')
sys.stdout.flush()
time.sleep(0.5)
print(".", end='')
sys.stdout.flush()

答案2

您也可以使用end=""语法来做到这一点。

print("this ",end="")
print("will continue on the same line")
print("but this wont")

将返回

this will continue on the same line
but this wont

因此下面的方法同样有效。

import time
print ("Ok, I know how to write programs in Python now.",end="")
time.sleep(0.5)
print (".",end="") # This should print on the same line as the previous print statement.
time.sleep(0.5)
print (".") # ... As should this one

答案3

这难道不简单吗?:

import time
print ("Ok, I know how to write programs in Python now."),
time.sleep(0.5)
print ("."), # This should print on the same line as the previous print statement.
time.sleep(0.5)
print (".") # ... As should this one

答案4

这也可以通过输入来完成吗?

print("THIS IS A TEST AREA")
print()
print("TETST OF SAME LINE INTERACTION")
print("X:  ", end="") #This works Fine
input("")
time.sleep(0.5)  #This however dew to python3 wont?
print("     STAR")

这个输出看起来像这样...

THIS IS A TEST AREA

TETST OF SAME LINE INTERATION
X:  
     STAR
>>> 

相关内容