Thursday, April 18, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 18464  / 2 Years ago, tue, june 14, 2022, 8:41:12

Is there a way to execute multiple statemens while performing them in one line, like this:



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


... So the output should be:



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


*Waits .5 seconds


More From » python

 Answers
2

In Python 2, the print statement automatically adds a line feed, so you need to use sys.stdout.write() instead. You will also have to import sys. The code you have written should look like this instead:



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(".")


In Python 3, print is a function accepting keyword arguments. You can use the end keyword argument to specify what should be placed after your string. By default it's a new line character, but you can change it to an empty string:



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='')


Also, remember that streams are buffered, so it's better if you flush them:



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()

[#36815] Thursday, June 16, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
afyess

Total Points: 437
Total Questions: 120
Total Answers: 107

Location: San Marino
Member since Fri, Jul 3, 2020
4 Years ago
;