Some basic questions
Dave Kuhlman
dkuhlman at rexx.com
Wed Mar 26 16:20:26 EST 2003
Brian Christopher Robinson wrote:
> I just began writing Python today and have a few basic questions:
>
> How can I read a single character from the standard input without
> consuming any more input?
The read method on file objects takes an optional size parameter. See
section 2.2.8 "File Objects" in the Python Library Reference in the Python
standard documentation set. Maybe the following will do what you need:
import sys
c = sys.read(1)
>
> Is there any way to write a boolean function? I wanted to write a simple
> is_alpha function (which may be in the standard library but I'm leanring),
> and this is what I came up with:
>
> def is_alpha(c) :
> letters = re.compile("[a-zA-Z]")
> return letters.match(c)
>
> Instead of checking for true or false I check to see if None is returned,
> but that seems a little kludgy.
Python 2.3 has (will have) a Boolean type (with values True and False). If
you are sure that all your users will be using Python 2.3, then use that.
However, the "if" statement treats None and several other values as false.
This is explained in the Python Library Reference in section 2.2.1 "Truth
Value Testing". So you can do something like the following:
alpha = is_alpha(c)
if alpha:
# it's alpha
else:
# it's not alpha
>
> How can I print to standard out without printing a newline? It seems that
> the print statement always adds a newline and I haven't found any other
> outputting functions yet.
Use this:
import sys
sys.stdout.write('some stuff')
sys.stdout.write('more stuff')
The print statement is just a convenient wrapper for sys.stdout. And, by
the way, if you change the value of sys.stdout (to another file type
object, of course), you can change where the print statement sends its
output.
Hope this helps.
--
Dave Kuhlman
dkuhlman at rexx.com
http://www.rexx.com/~dkuhlman
More information about the Python-list
mailing list