On Mar 19, 11:52 pm, Chris Rebert <c...@rebertia.com> wrote: > 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
The OP asked for an emulation of printf(), which doesn't have softspacing and other party tricks. > 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. It is one of those things that it is good to know, perhaps not so good to practice ... somewhat akin to the English definition of a Scots gentleman: "A man who can play the bagpipes but doesn't". Cheers, John -- http://mail.python.org/mailman/listinfo/python-list