0

Is there an alternative to writing 'codec' four times in the argument list?

codec = 'XVID'
fourcc = cv.CV_FOURCC(codec[0], codec[1], codec[2], codec[3])

When I do this the argument is just one because the result of ','.join(ls) is a string. Is there a way to pass four arguments without having to do what is in the above example?

codec = 'XVID'
ls = list(codec)
fourcc = cv.CV_FOURCC(','.join(ls))
いちにち
  • 417
  • 6
  • 16

1 Answers1

4

Use *args argument unpacking:

cv.CV_FOURCC(*codec)

Any iterable passed using a * prefix is unpacked into separate arguments; a string is an iterable too and results in len(string) arguments, each a single character:

>>> codec = 'XVID'
>>> def demo(arg1, arg2, arg3, arg4):
...     print arg1, arg2, arg3, arg4
... 
>>> demo(*codec)
X V I D

You can use ** to treat an argument as a mapping of keyword parameters (each key-value pair becoming an argument), and the same syntax in a function signature lets you capture variable arguments as a tuple or mapping, respectively. See What does ** (double star) and * (star) do for parameters?

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343