-1
dict = {}
def colors(col):
  if col == "red":
    return "\033[31m"
  elif col == "green":
    return "\033[32m"
  elif col == "yellow":
    return "\033[33m"
  elif col == "blue":
    return "\033[34m"
  elif col == "magenta":
    return "\033[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?

Emi OB
  • 2,814
  • 3
  • 13
  • 29
Zein
  • 3
  • 1
  • The output is buffered. You need to pass `flush=True` to `print`. `print(f"{colors(y)}{char}",end="", flush=True)` – hamdanal Dec 29 '22 at 08:51

1 Answers1

1

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 "\033[31m"
  elif col == "green":
    return "\033[32m"
  elif col == "yellow":
    return "\033[33m"
  elif col == "blue":
    return "\033[34m"
  elif col == "magenta":
    return "\033[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")
Marc Sances
  • 2,402
  • 1
  • 19
  • 34