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

Chris Rebert clp2 at rebertia.com
Thu Mar 19 09:27:47 EDT 2009


On Thu, Mar 19, 2009 at 6:13 AM, John Machin <sjmachin at lexicon.net> wrote:
> On Mar 19, 11:52 pm, Chris Rebert <c... at rebertia.com> wrote:
>> On Thu, Mar 19, 2009 at 5:43 AM, Mr. Z <no... 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])
>>
>> > 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.
<snip>
>> def printf(format, *args):
>>     print format % args
>
> The OP asked for an emulation of printf(), which doesn't have
> softspacing and other party tricks.

Well, his implementation had the same issues, so I assumed he was
going for something merely somewhat printf()-like rather than exactly
the same. Though I suppose you might as well go all the way if you're
doing something impractical like this. :)

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list