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

star.public at gmail.com star.public at gmail.com
Tue Jul 17 12:46:37 EDT 2007


On Jul 17, 2:19 am, Paddy <paddy3... at googlemail.com> wrote:
> On Jul 17, 1:10 am, 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? I'm thinking some general common placeholder,
> > say %x (currently it's hex..) could be used.
>
> > output = '%x foo %x bar" % (foo_count, bar_count).
> > Since % by definition is string formatting, the operator should be
> > able to infer how to convert each of the argument into strings.
>
> > If the above is the case, we could've avoided all those exceptions
> > that happen when a %d is specified but say a string is passed.
>
> > Thanks,
> > Karthik
>
> '%s' might be what your after as a more 'general purpose' moifier.
>
> - Paddy.- Hide quoted text -
>
> - Show quoted text -

It is good for that; I generally use %s until I decide that something
needs picky formatting.

--
a = '%s Weaver' % random.choice(['Lani','Star','Azure'])
a += 'is strange.'




More information about the Python-list mailing list