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

Mr. Z noone at XSPAMbellsouth.net
Thu Mar 19 08:43:00 EDT 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
arg[0]
          print arg[0] % (arg[1], arg[2])

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

-- 

---------------------------
Remove XSPAM





More information about the Python-list mailing list