Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the asterisk in "replace(*something)" for? (python) [duplicate]

Tags:

python

Possible Duplicate:
What does *args and **kwargs mean?

I' just reading Mining the social web and encountered a python syntax that I can't figure out:

transforms = [(', Inc.', ''), (', Inc', ''), (', LLC', ''), (', LLP', '')]

"google, Inc.".replace(*transforms[0])

But if I type

*transforms[0]

in the interpreter, it says it is invalid syntax. I googled it, but the python docu really is not up for the job.

So what does the asterisk means here please? Thank you all.

like image 930
dgg32 Avatar asked Sep 02 '12 12:09

dgg32


1 Answers

The *argument format in python means: use all elements in the sequence argument and pass them as arguments to the function.

In this specific case, that translates to:

"google, Inc.".replace(', Inc.', '')

This is easiest demonstrated:

>>> def foo(arg1, arg2):
...     print arg1, arg2
...
>>> arguments = ('spam', 'eggs')
>>> foo(*arguments)
spam, eggs

You can also use the **kw double star format to pass in keyword arguments:

>>> def foo(arg1='ham', arg2='spam'):
...     print arg1, arg2
...
>>> arguments = dict(arg2='foo', arg1='bar')
>>> foo(**arguments)
bar, foo

and you can use the same spelling in a function definition to capture arbitrary positional and keyword arguments:

>>> def foo(*args, **kw):
...     print args, kw
...
>>> foo('arg1', 'arg2', foo='bar', spam='eggs')
('arg1', 'arg2'), {'foo': 'bar', 'spam': 'eggs'}
like image 89
Martijn Pieters Avatar answered Oct 03 '22 15:10

Martijn Pieters