Home > Mobile >  How do I add multiple string arguments to my typing function in Python?
How do I add multiple string arguments to my typing function in Python?

Time:12-10

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?

CodePudding user response:

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.

CodePudding user response:

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:
       ...
  • Related