1

I made a type() function which functions similarly to print except it types character by character. The problem is, when I try to implement multiple str arguments it just prints everything at once.

The code I used originally was:

import sys
import time
def type(text):
  for char in text:
    sys.stdout.write(char)
    sys.stdout.flush()
    time.sleep(0.05)
  print()

In order to add more str arguments, I did:

import sys
import time
def type(*text):
  for char in text:
    sys.stdout.write(char)
    sys.stdout.flush()
    time.sleep(0.05)
  print()

In practice, however, it usually just prints everything at once, like a normal print function. Any pointers?

  • `type()` is a built-in function in Python, try to avoid [redefining any of the built-in functions](https://docs.python.org/3/library/functions.html). – Alexander L. Hayes Dec 09 '22 at 21:06
  • The `*text` indicates that `text` is now a tuple instead of a string. There would need to be an additional loop to iterate over each tuple in the input, *then* iterate over each character in the string. – Alexander L. Hayes Dec 09 '22 at 21:07
  • 1
    Does this answer your question? [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Alexander L. Hayes Dec 09 '22 at 21:10

2 Answers2

1

If text is a list, and the length of it varies, you can do:

def type(text):
for string in text:
    for char in string:
    sys.stdout.write(char)
    sys.stdout.flush()
    time.sleep(0.05)
  print()

So you loop through the lists for each string, and for each string you loop through all the characters.

Iustin
  • 70
  • 5
0

In the case of using the *args pattern

def func(*args):
    ...

func(a, b, c) # Then args is a tuple (a, b, c) inside the function.

args will be a tuple inside the function. Your first function has text which is a string, while in your second text is a list of strings. So you'll need to either combine them all into one string like text = ''.join(text) or iterate through each

for string in text:
   for char in string:
       ...
user9794
  • 186
  • 4