On Thu, Mar 19, 2009 at 5:43 AM, Mr. Z <no...@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]) > > 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])
def printf(format, *args): print format % args Although I fail to see the point in doing this. All you're doing is trading the use of the % operator for a function call. Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list