In a dynamic language, why % operator asks user for type info?

Karthik Gurusamy kar1107 at gmail.com
Tue Jul 17 02:33:53 CEST 2007


On Jul 16, 5:18 pm, Dan Bishop <danb... at yahoo.com> wrote:
> On Jul 16, 7:10 pm, Karthik Gurusamy <kar1... at gmail.com> wrote:> Hi,
>
> > The string format operator, %, provides a functionality similar to the
> > snprintf function in C. In C, the function does not know the type of
> > each of the argument and hence relies on the embedded %<char>
> > specifier to guide itself while retrieving args.
>
> > In python, the language already provides ways to know the type of an
> > object.
>
> > So in
>
> > output = '%d foo %d bar" % (foo_count, bar_count),
> > why we need to use %d?
>
> In order to distinguish between, for example:
>
>
>
> >>> '%c' % 42
> '*'
> >>> '%d' % 42
> '42'
> >>> '%e' % 42
> '4.200000e+01'
> >>> '%f' % 42
> '42.000000'
> >>> '%g' % 42
> '42'
> >>> '%i' % 42
> '42'
> >>> '%o' % 42
> '52'
> >>> '%r' % 42
> '42'
> >>> '%s' % 42
> '42'

Thanks. The above surprised me as I didn't expect that %s will accept
42.

Looks like the implicit conversion doesn't work the other way.

>>> '%s' % 42
'42'
>>> '%d' % '42'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int argument required
>>>

Looks like %s can be used even when I'm sending non-strings.
>>> '%s foo %s bar' % (25, 25.34)
'25 foo 25.34 bar'
>>>

So %s seems to serve the multi-type placeholder.

Karthik


> >>> '%u' % 42
> '42'
> >>> '%x' % 42
>
> '2a'





More information about the Python-list mailing list