Home > Blockchain >  How do make a break in the middle of a print statement in python?
How do make a break in the middle of a print statement in python?

Time:01-06

I want to print "txt" but want to have a break without making a new line.

import time
txt = ["What is the answer to time the universe and everything?",42]
for i in range(0,2):
  print(txt[i], end = "")
  time.sleep(1)

Is there an easier way of doing this? And what if I want to make several different timed breaks?

CodePudding user response:

Add flush=True to the print call to force it to print to the screen immediately instead of waiting for a new line.

If you iterate over the list instead of a hard-coded range corresponding to its indices, you can freely add more elements to the list without having to change other code:

import time

txt = ["What is the answer to time", "the universe", "and everything?", 42]
for msg in txt:
  print(msg, end = " ", flush=True)
  time.sleep(1)

If you can automate the rules around when to pause (say, after each word, or each letter), then you don't need to break the text up into a list:

import time

txt = "What is the answer to life, the universe, and everything?  42"
for word in txt.split():
    print(word, end=" ", flush=True)
    time.sleep(1)
import time

txt = "What is the answer to life, the universe, and everything?  42"
for letter in txt:
    print(letter, end="", flush=True)
    time.sleep(0.1)

CodePudding user response:

The solution is simple: add flush=True to get print(txt[i], end = "", flush=True)

  •  Tags:  
  • Related