[Tutor] string splitting

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 9 Dec 2001 20:03:38 -0800 (PST)


Hi Kirk,


On Sun, 9 Dec 2001, Kirk Bailey wrote:

> ok, in IDLE I created a variable, listnamemembers, and inserted a
> bunch of info in it, with triple quotes.
> listnamemembers = """me@here.net
> you@there.org
> Me@here2.com
> everybody@earth.edu
> nobody@domainerror.cc
> """

'listnamemembers' here is a string.  Although we as humans might consider
it a bunch of lines, Python's instincts is to treat strings as a sequence
of single characters, which is why when we do a 'for' loop across it:

> for i in listnamemembers:
> 	print i

Python will go through each character in 'listnamemembers'.  That's why
the program prints every character, one per line.  Personally, I like
this, because it allows certain things to be easy, like this:

###
>>> def isVowel(letter):
...     return letter in 'aeiouAEIOU'
... 
>>> isVowel('z')
0
>>> isVowel('e')
1
###



Anyway, back to your question: what we want to do, instead, is tell Python
to "split" between the lines, to break our string down between new lines.  
We can do this if we use the string.split() function, like this:

###
>>> string.split(listnamemembers, '\n')
['me@here.net', 'you@there.org', 'Me@here2.com', 'everybody@earth.edu',
 'nobody@domainerror.cc', '']
###


That gives us a list of single lines, exactly what you're looking for!
It's also something we can feed into a for loop:

###
>>> for address in string.split(listnamemembers, '\n'):
...     print "Here's one email address: ", address
... 
Here's one email address:  me@here.net
Here's one email address:  you@there.org
Here's one email address:  Me@here2.com
Here's one email address:  everybody@earth.edu
Here's one email address:  nobody@domainerror.cc
Here's one email address:  
###


In the command above, '\n' is the "newline" string, so we're telling
Python to split up listnamemembers between new lines.  We can be silly and
split against something, else, like the '@' symbol:

###
>>> string.split(listnamemembers, '@')
['me', 'here.net\nyou', 'there.org\nMe', 'here2.com\neverybody',
 'earth.edu\nnobody', 'domainerror.cc\n']
###

Actually, this might actually be useful, since splitting between '@'
allows us to pull out a user's name from their email address.  
string.split() is a very good tool, and worth using.



> In total confusion,

Hey, don't worry about it; it'll make sense eventually.  Programming take
practice, so don't be too hard on yourself.  Just wondering, are you
reading through a tutorial from the Python web site, or something else?

I'm going to get some dinner now.  I'll talk to you later!