[Tutor] Breaking string at commas

Timothy Brauch tmbrau00@centre.edu
Mon, 12 Mar 2001 12:49:18 -0500

The string.split from the string module will break up a string into a
list of parts of the string.  You can choose what to use for a break
point.  THe following example uses <> as a break point.

>>> import string
>>> raw_string='I hope this will be split after this <> but before this.'
>>> new_strings=string.split(raw_string,'<>')
>>> print new_strings
['I hope this will be split after this ', ' but before this.']

By default, if you don't specify a pattern to break by, it will break by
white space.  Like this,

>>> raw_string='This is a string of words'
>>> new_string=string.split(raw_string)
>>> print new_string
['This', 'is', 'a', 'string', 'of', 'words']

Now, try this,

>>> db_entry='item_1, item_2, item_3'
>>> format_db=string.split(db_entry,',')
>>> print format_db
['item_1', ' item_2', ' item_3']

Hmm, if you look closely at the items in format_db, it is ' item_2',
there is some whitespace at the beginning.  Instead, let's try this:

>>> db_entry='item_1, item_2, item_3'
>>> format_db=string.split(db_entry,' ,')
>>> print format_db
['item_1, item_2, item_3']

There, that works better.

Hopefully that will help you to break up the strings where you want

 - Tim


"Shawhan, Douglas (GEAE, GECC)" wrote:

I am trying to write a script that will take comma seperated text from a
file, break the strings into seperate units at the linefeeds then
seperate the comma seperated text into strings, insert html formatting
then output the whole shebang into an html file. I have figured out how
to read the info from the flat files and squirt them to html with
formatting (do what you can, if it's all that you can! :-).

---------begin ugly script---------------
f.write('<html><h1><b>MOVES/INSTALLS</b></h1><body bgcolor=white><font
face=\"arial,helvetica\" size=\"2\"><table width=580><tr><td
----------end ugly script--------------

Now the tricky part for me is: How can I first bust the files apart at
the line breaks, then search for the unique id in the resulting output?

The other trick is: How am I going to bust apart those strings within
the chosen output to insert the formatting?

Feel free to poke me in the eye or point me to an example in a manual (I
have the tutorial from the website and a copy of Lutz and Ascher's
so-far excellent "Learning Python")