[Tutor] parsing x is y statements from stdin

Blake Winton bwinton@latte.ca
Fri Jul 18 10:17:00 2003


> I'm wondering if I can't treat each line of stdin as a list where list
> [0] is the key, list[1] is the verb, list[2] is the right hand 
> side 'target'.  I'm just completely unsure of how to go about doing 
> that.

Here's what I did, so that you can see my train of thought.
(If you're using an earlier version of Python, and you can't copy
 the following example, email me, and I'll show you the backwards-
 compatible way to do it.)

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = "He is a python programmer"
>>> help( x.split )
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator.

>>> x.split( 3 )
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: expected a character buffer object
>>> x.split( None, 3 )
['He', 'is', 'a', 'python programmer']
>>> x.split( None, 2 )
['He', 'is', 'a python programmer']


>>> import sys
>>> x = sys.stdin.readline()
You get the idea now.
>>> x.split( None, 2 )
['You', 'get', 'the idea now.\n']
>>> help( x.strip )
Help on built-in function strip:

strip(...)
    S.strip([chars]) -> string or unicode

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping
>>> x.strip().split( None, 2 )
['You', 'get', 'the idea now.']

How does that look to you?  Mostly what you wanted?

Later,
Blake.