[Tutor] Request for guidance about a python syntax
Peter Otten
__peter__ at web.de
Mon Dec 19 18:10:40 CET 2011
Jerry Hill wrote:
> On Mon, Dec 19, 2011 at 10:54 AM, Ganesh Borse <bganesh05 at gmail.com>
> wrote:
>
>> I could know the use of unpack_from, but I could not understand the "fmt"
>> part, i.e *"%dH" % nframes * nchannels*.
>> Can you pls help me know, what is the purpose of two "%" signs in this
>> statement?
>>
>>
> That's python's string formatting. See
> http://docs.python.org/library/stdtypes.html#string-formatting-operations
> for
> details. Basically, it's building the format for the call to unpack_from
> on the fly. The "%dH" portion is calling for a single decimal value to
> become part of the string (that's the "%d" portion). That value comes
> from
> multiplying nframes by nchannels. So, for example, if nframes = 10 and
> nchannels = 24, then the string becomes "240H". That, in turn, tells the
> program to unpack a sequence of 240 unsigned short values from the buffer.
Close, but % and * have the same operator precedence. Therefore the
expression
"%dH" % nframes * nchannels
is evaluated as
(%dH" % nframes) * nchannels
So
>>> nframes = 2
>>> nchannels = 3
>>> "%dH" % nframes
'2H'
>>> "%dH" % nframes * nchannels
'2H2H2H'
The original script still works because multiplying a string by an integer
repeats the string, and the format "2H2H2H" is equivalent to "6H", but
"%dH" % (nframes * nchannels)
is probably a bit more efficient, especially for large values of nchannels.
More information about the Tutor
mailing list