If
you’re working with text files you’ll probably want to extract some specific
substring which is implemented in strings. For example you want to split and
collect the first and second half of e-mail address. First half of e-mail
address is before the @ sign and second half is after the @ sign. Let’s look at
the sentence:
From
stephen.marquard@ uct.ac.za Sat Jan 5 09:14:16 2008
To
pull out email by using the find method and string slicing. First, we will find
the position of the @ sign. And then we will use string slicing to extract the
portion of the string which we are looking for.
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' atpos = data.find('@') print atpos sppos1 = data.find(' ') print sppos1 sppos2 = data.find(' ', atpos) print sppos2 host1 = data[sppos1+1:atpos] host2 = data[atpos+1:sppos2] print host1 print host2
Output
<21 4 31 stephen.marquard uct.ac.za
We
use a version of the find method which allows us to specify a position in the
string where we want find to start looking.
Nema komentara:
Objavi komentar