【问题标题】:Pass variable number of parameters into a function then call a function within my function with those parameters将可变数量的参数传递给一个函数,然后使用这些参数在我的函数中调用一个函数
【发布时间】:2014-06-24 08:41:58
【问题描述】:

如果这个问题已经得到解答,我深表歉意 - 我怀疑这很简单 - 但我不知道该怎么做。

演示我想做的事情更容易。

vflag=True

def printv(*prargs):
    if vflag:
        print prargs
#       print *prargs gives a syntax error, unsurprisingly


printv("hello", "there", "world")
printv("hello", "again")

我希望输出是

hello there world
hello again

我得到(当然)

('hello', 'there', 'world')
('hello', 'again')

【问题讨论】:

    标签: python function parameters python-2.x


    【解决方案1】:

    你应该这样做:

    def printv(*prargs):
        if vflag:
            print ' '.join(prargs)
    
    >>> printv("hello", "there", "world")
    hello there world
    

    string.join(iterable) 返回由指定字符串分隔的列表中所有元素的字符串,在本例中为 ' '(一个空格)。

    【讨论】:

    • 嗯,这很简单——而且很快。真的非常感谢。
    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2013-03-28
    • 2021-11-09
    相关资源
    最近更新 更多