Emulate a printf() C-statement in Python???

Mr. Z noone at XSPAMbellsouth.net
Thu Mar 19 10:05:08 EDT 2009


"Andrii V. Mishkovskyi" <mishok13 at gmail.com> wrote in message
news:mailman.2185.1237467269.11746.python-list at python.org...
On Thu, Mar 19, 2009 at 2:43 PM, Mr. Z <noone at xspambellsouth.net> wrote:
> I'm trying emulate a printf() c statement that does, for example
>
> char* name="Chris";
> int age=30;
> printf("My name is %s", name);
> printf("My name is %s and I am %d years old.", %s, %d);
>
> In other words, printf() has a variable arguement list the we
> all know.
>
> I'm trying to do this in Python...
>
> class MyPrintf(object):
> # blah, blah
> def myprintf(object, *arg):
> # Here I'll have to know I NEED 2 arguments in format string
> arg[0]
> print arg[0] % (arg[1], arg[2])

Note: you can, of course, use any name for the instance variable in
methods, but 'self' is considered a de-facto standard, not 'object'.
Besides, you're overriding builtin which is considered a bad practice.

>
> name="Chris"
> age=30
> printf=MyPrintf()
> printf.myPrintf(("My name is %s and I am %d years old.", name, age)
> will of course print...
> My name is Chris and I am 42 years old.
>
> But
> printf.myPrintf(("My name is %s.", name)
> of course gives....
> Index error: list index out of range
>
> How can I generalize the print call in the myprintf() function to do this?
>
> print arg[0] % (arg[1])
> print arg[0] % (arg[1], arg[2])
> print arg[0] % (arg[1], ..., arg[n])

It's quite simple:
def printf(fmt, *args):
    print fmt % args

>
> --
>
> ---------------------------
> Remove XSPAM
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Too simple, I love it!

-- 
Wbr, Andrii V. Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.





More information about the Python-list mailing list