Pass variable number of parameters into a function then call a function within my function with those parameters

StackOverflow https://stackoverflow.com/questions/23516649

Question

My apologies if this has been answered - I suspect it's very simple - but I can't see how to do it.

It's easier to demonstrate what I want to do.

vflag=True

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


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

I want the output to be

hello there world
hello again

and I get (of course)

('hello', 'there', 'world')
('hello', 'again')
Was it helpful?

Solution

You should do it as:

def printv(*prargs):
    if vflag:
        print ' '.join(prargs)

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

The string.join(iterable) returns a string of all the elements in the list separated by the specified string, in this case ' ' (a whitespace).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top