In a dynamic language, why % operator asks user for type info?
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
> >>> '%e' % 42
> >>> '%f' % 42
> >>> '%g' % 42
> >>> '%i' % 42
> >>> '%o' % 42
> >>> '%r' % 42
> >>> '%s' % 42
Thanks. The above surprised me as I didn't expect that %s will accept
Looks like the implicit conversion doesn't work the other way.
>>> '%s' % 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.
> >>> '%u' % 42
> >>> '%x' % 42
More information about the Python-list