how to extract columns like awk $1 $5
Craig Ringer
craig at postnewspapers.com.au
Fri Jan 7 12:34:18 EST 2005
On Sat, 2005-01-08 at 01:15, Anand S Bisen wrote:
> Hi
>
> Is there a simple way to extract words speerated by a space in python
> the way i do it in awk '{print $4 $5}' . I am sure there should be some
> but i dont know it.
The 'str.split' method is probably what you want:
.>>> x = "The confused frog mumbled something about foxes"
.>>> x.split()
['The', 'confused', 'frog', 'mumbled', 'something', 'about', 'foxes']
.>>> x.split(" ")[4:6]
['something', 'about']
so if 'x' is your string, the rough equivalent of that awk statement is:
.>>> x_words = x.split()
.>>> print x_words[4], x_words[5]
or perhaps
.>>> print "%s %s" % tuple(x.split()[4:6])
--
Craig Ringer
More information about the Python-list
mailing list