Re: how to extract columns like awk $1 $5

Discussion in 'Python' started by Craig Ringer, Jan 7, 2005.

  1. Craig Ringer

    Craig Ringer Guest

    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
    Craig Ringer, Jan 7, 2005
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. gorda
    Replies:
    2
    Views:
    542
    Andrew Shitov
    Oct 21, 2003
  2. Anand S Bisen

    how to extract columns like awk $1 $5

    Anand S Bisen, Jan 7, 2005, in forum: Python
    Replies:
    7
    Views:
    1,917
    Carl Banks
    Jan 8, 2005
  3. gorda
    Replies:
    3
    Views:
    147
    Barry Kimelman
    Oct 21, 2003
  4. A. Farber
    Replies:
    9
    Views:
    192
    Uri Guttman
    Jun 3, 2009
  5. Rudra Banerjee

    awk like usage in python

    Rudra Banerjee, Nov 9, 2012, in forum: Python
    Replies:
    0
    Views:
    139
    Rudra Banerjee
    Nov 9, 2012
Loading...

Share This Page