Passing multiple values to a function call (Python)
import re
def strip_tags(value):
"Return the given HTML with all tags stripped."
return 开发者_C百科re.sub(r'<[^>]*?>', '', value)
I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values at once?
Thanks
Python offers a way to use arbitrary-length argument lists:
def myfunc(*args):
for argument in args:
print "myfunc was given", argument
If you put *args
in your function definition, all values passed to the function are available as a tuple called args
. Note that you can also put additional arguments before *args
,
like
def my_other_func(name, *args):
so the first argument will be available as name
, the rest will be in the tuple args
.
It is convention, but not neccessary, to call this parameter args
. As long as there's an asterisk in front of it, you can call it whatever you like.
Could you use a loop.
for value in values:
strip_tags(value)
You could pass in value
as an array of strings, and then return the array of cleaned values.
If the values are independent of each other, then don't modify strip_tags, just change how you call it:
values = [some_value, another_value]
values = [strip_tags(v) for v in values]
# values[0] is now the strip_tags version of the old values[0]
# similar to values[0] = strip_tags(values[0]), except for every item
If the values are related, such as being adjacent pieces of the same file, then concatenate them before using strip_tags:
values = [some_value, another_value]
result = strip_tags("".join(values))
# note result is single string
import re
def strip_tags(values):
return map(lambda i: re.sub(r'<[^>]*?>', '', i), values)
here is a function written over the function you have provided. this would take in a list of values and return the corresponding processed list:
import re
def strip_tags_list(values):
return map(strip_tags, values)
note: this would work on python 2.6 and earleir versions. on python 3.0, you would have to explicitly convert the result of map() to list using list().
精彩评论