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

Mr. Z noone at XSPAMbellsouth.net
Thu Mar 19 13:43:00 CET 2009

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
          print arg[0] % (arg[1], arg[2])

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.

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])


Remove XSPAM

More information about the Python-list mailing list