1

I have code to make running text:

from time import sleep
import os

def run(text):
    for i in text:
        print (i, end="", flush=True)
        sleep(0.07)

teks = " Hello\n"
teks2 = " world"
run(teks)

run(teks2)

and output

hello
world

I want to display the results like in the youtube video TypeWriter Effect In ReactJS Tutorial.

Can you help me please?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ardians.sh
  • 19
  • 7

3 Answers3

1

I think this does essentially the same thing as what's in the video:

from time import sleep
CPS = 3  # Update speed in Characters Per Second.

def run(text, width=60, delay=1/CPS):
    text = text.replace('\n', '')  # Removed any newlines.
    for i in range(len(text)+1):
        print('\r' + text[:i].center(width), end="", flush=True)
        sleep(delay)

    for i in range(len(text)+1, -1, -1):
        print('\r' + text[:i].center(width), end="", flush=True)
        sleep(delay)

run("Hello\n")
run("world")

The code above can be streamlined slightly by applying the DRY (Don't Repeat Yourself) principle of software development:

from itertools import chain
from time import sleep
CPS = 3  # Update speed in Characters Per Second.

def run(text, width=50, delay=1/CPS):
    for line in text.splitlines():
        interval = len(line) + 1
        for i in chain(range(interval), range(interval, -1, -1)):
            print('\r' + line[:i].center(width), end="", flush=True)
            sleep(delay)

run("Hello\nworld")
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Here you are:

EDITED:

from time import sleep


def run(word):
    for letter in word:
        print(letter, end="", flush=True)
        sleep(0.5)

    print("\r", end="")

run("Hello")
run("world !")

You were calling the function twice with different arguments, so the loop would run twice as well. Next, you had the line-breaking character in your String (I mean "\n"), this will split the lines, so end="" had no effect in your code.

jozpac
  • 84
  • 7
0

here is the solution:

def run(text):
    for i in text:
        print(i, flush=True, end='')
        sleep(0.07)
    print('\r', end='')
crackanddie
  • 688
  • 1
  • 6
  • 20