[Tutor] string splitting
Sun, 9 Dec 2001 20:03:38 -0800 (PST)
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 = """firstname.lastname@example.org
'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'
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')
['email@example.com', 'firstname.lastname@example.org', 'Me@here2.com', 'email@example.com',
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: firstname.lastname@example.org
Here's one email address: email@example.com
Here's one email address: Me@here2.com
Here's one email address: firstname.lastname@example.org
Here's one email address: email@example.com
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',
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!