[Tutor] Reading in data files

Steven D'Aprano steve at pearwood.info
Mon Mar 14 23:37:28 CET 2011


Marc Tompkins wrote:
> On Mon, Mar 14, 2011 at 1:02 PM, Marc Tompkins <marc.tompkins at gmail.com>wrote:
> 
>> On Mon, Mar 14, 2011 at 12:59 PM, paige crawford <
>> plcrawford at crimson.ua.edu> wrote:
>>
>>> How do I split them by spaces?
>>>
>>> Google "Python split".
>> That might have been a bit abrupt... but (in general) the Tutor list is
> happy to help point you in the right direction, not do your homework for
> you.  I even gave you a big hint by writing it as split() in my original
> message.  (It's a string function.)


That's a bit harsh. Telling somebody about the existence and use of a 
built-in function isn't "doing your homework for you" unless the 
homework is "Write down what the string.split method does", in which 
case, the teacher is too lazy for words :)

Paige, you are reading lines one at a time from a file. Each line is a 
string. You can split the strings on any delimiter using the split method:

 >>> mystr = "breakfast = spam and eggs -- spam spam spam glorious SPAM!!!"
 >>> mystr.split("--")
['breakfast = spam and eggs ', ' spam spam spam glorious SPAM!!!']
 >>> mystr.split("=")
['breakfast ', ' spam and eggs -- spam spam spam glorious SPAM!!!']

The result is a list of substrings. You can then assign them to new 
variables and process them further.

You may also find the string strip() method useful for getting rid of 
spaces around substrings.

You can also look up functions and methods in the interactive 
interpreter using the help() function. If your Python is configured 
correctly, at the Python prompt, you can say:

help()

to start the help system, or go directly to a particular method or 
function, e.g.:

help(len)  # help about the ``len`` built-in function
help(''.split)  # help about the string split method

Notice that you don't include parentheses after the function or method.


-- 
Steven


More information about the Tutor mailing list