I want to write a printf() function, similar to the one that C has, in Python. Here is the straightforward way to do it:
def printf(format, *args):
print format % (args),
The problem is that the print, statement (including the comma) leaves a trailing whitespace character after printing something. This makes my Python implementation of printf work even more differently from the one in C:
# Python
>>> printf("Hello"); printf("World!")
>>> Hello, World!
/* C */
#include
How do I fix this?
hmm... it's missing <stdio.h> in the C example O.o
#include <stdio.h>
how come?
I recall typing it in!
#include<conio.h>
instead of main write void main(void)
it works when you type it an 'answer' box, but not when it's inside the initial question box.
I know my C example is not standard C :-P but it's just supposed to illustrate the problem.
cmon, Python pros out there! a printf() would be useful in python.
thanks
How do I write a printf function using sys.stdout.write?
I mean, how do I do formatting?
In python the % operator formats a string with the replacement parameters, and returns the resulting string. Just because you normally do it as part of a print statement doesn't limit the behavior to printing. >>> s = "%s, %s!" % ("Hello", "World") >>> s 'Hello, World!' No printing necessary.
Join our real-time social learning platform and learn together with your friends!