[Tutor] Printing to Screen

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed Jul 30 17:44:43 2003


On Wed, 30 Jul 2003, Jeff Shannon wrote:

> DORSEY_EDMUND_K@LILLY.COM wrote:
>
> >
> > Is there a way to print but not have it do a new line
> >
> > For instance in java you have print and println in C you have to
> > specify the end of line marker.
>
> If you need finer control over the output than print gives you, then you
> can import sys and use sys.stdout.write() -- sys.stdout is a file-like
> object that represents your current standard output, and print
> internally writes to sys.stdout.


Hi Dorsey,


In fact, if you use sys.stdout.write(), it'll feel almost exactly like C's
printf() function.


For example, the following C code:

/*** C code **/
int x = 20;
printf("%d squared is equals to: %d\n", x, x*x);
/*************/



has a direct translation in Python:

### Python code ###
x = 20
sys.stdout.write("%d square is equal to: %d\n" % (x, x*x))
###


So if you need printf()-like functionality, use the write() method of the
stdout file object.  You can use the String Formatting operations to
interpolate variable values into your string.


If you find yourself doing a lot of sys.stdout.write()'s, you can simplify
your typing by using a helper variable:

###
>>> import sys
>>> sys.stdout.write
<built-in method write of file object at 0x80fef60>
>>> write = sys.stdout.write
>>> write
<built-in method write of file object at 0x80fef60>
>>> write("hello world\n\nThis is a test!\n")
hello world

This is a test!
###


Python allows us to pull any object's method and make it look like a
simple function, and the example above shows a good use of it.



Good luck!