有没有办法将字符串列表作为逗号分隔的字符串传递给python中的函数的args

问题描述

我想不受限制地从用户那里获取字符串,并将其作为不同参数传递给函数,例如

user_input = "Hello World! It is a beautiful day."

我想将此以空格分隔的字符串作为参数传递给函数,即

func("Hello","World!","It","is","a","beautiful","day.")

我无法传递列表或元组,它必须是多个字符串。我是python的新手,很抱歉,如果解决方案很简单

解决方法

您可以为此使用*args(如果需要,可以使用**kwargs)。 (More details here

def func(*args):
    for s in args:
        print(s)

然后在您的呼叫中,您可以使用*split的结果分解为单独的参数。 (有关extended iterable unpacking的更多信息)

>>> user_input = "Hello World! It is a beautiful day."
>>> func(*user_input.split())
Hello
World!
It
is
a
beautiful
day.