Not printing letters one by one on one single line

Question:

dict = {}
def colors(col):
  if col == "red":
    return "33[31m"
  elif col == "green":
    return "33[32m"
  elif col == "yellow":
    return "33[33m"
  elif col == "blue":
    return "33[34m"
  elif col == "magenta":
    return "33[35m"

def seperator(x):
  colors1 = ["red","green","yellow","blue","magenta"]
  for char in x:
    y = random.choice(colors1)
    print(f"{colors(y)}{char}",end="")
    time.sleep(0.2)
    

seperator("MokeBeast")

I am trying to make python print the letters of this string with a 0.2 delay between each one on one single line.

I was expecting it to print out my string like this:

M (wait 0.2sec) o (wait 0.2sec) k (wait 0.2sec) e (wait 0.2sec) B (wait 0.2sec) e (wait 0.2sec) etc…

What keeps happening is that it does not print the letter one by one, instead it waits all those delays and then prints the string all in one like this: MokeBeast

How can I fix this?

Asked By: Zein

||

Answers:

You have to flush the standard output after each print to ensure they appear in between the waits:

import time
import sys
import random

dict = {}
def colors(col):
  if col == "red":
    return "33[31m"
  elif col == "green":
    return "33[32m"
  elif col == "yellow":
    return "33[33m"
  elif col == "blue":
    return "33[34m"
  elif col == "magenta":
    return "33[35m"

def seperator(x):
  colors1 = ["red","green","yellow","blue","magenta"]
  for char in x:
    y = random.choice(colors1)
    print(f"{colors(y)}{char}",end="")
    sys.stdout.flush() # <--- use this
    time.sleep(0.2)
    

seperator("MokeBeast")
Answered By: Marc Sances
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.