15

I'm looking for a way in python to achieve similar functionality to the unix cut utility. I know I can make a system call and process my data that way but I'd like to make it a bit more "pythonic" and do it with python libraries.

Example text

abcde:12345

I'd like to delimit on : and keep the second field:

cut -d':' -f2

to produce:

12345

thoughts?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
user735304
  • 447
  • 2
  • 5
  • 9
  • 1
    What about something like `echo 'abc:123:def:456' | cut -d':' -f1,3`? Is it possible to get fields 1 and 3 within from a single `split()` method, i.e. how to combine indices [1] and [3]? – Nikos Alexandris May 15 '13 at 12:01

4 Answers4

18

You can do:

string.split(":")[1]

where string is your text

manojlds
  • 290,304
  • 63
  • 469
  • 417
4

Try this:

'abcde:12345'.split(':')[1]
Trufa
  • 39,971
  • 43
  • 126
  • 190
John Machin
  • 81,303
  • 11
  • 141
  • 189
3

Sure:

for line in open('data.txt'):
    second_field = line.rstrip('\n').split(':')[1]

You can make it more configurable and even write your own with optparse or argparse...let us know more about what you're trying to do.

Henry
  • 6,502
  • 2
  • 24
  • 30
  • That code will include a newline if there are only 2 fields; it's best to do `line.rstrip('\n')` i.e. rstrip *before* split. – John Machin May 03 '11 at 01:04
  • @John thanks, and in the event that it has a different kind of newline, I haven't specified \n – Henry May 03 '11 at 01:14
  • It can't have have a different form of newline in text mode. You have stripped all/any trailing whitespace, which is overkill. If that is wanted, it should be done on each field of interest. – John Machin May 03 '11 at 01:34
  • @John I didn't realize that about text mode, thank you :) Also, I will fix it. – Henry May 03 '11 at 02:53
-3
cut -d: -f2

Try using this command.

  • 1
    The question is about how to use a cut operation *in Python*. OP gives the command you posted as the terminal command they wish to replicate *in Python*. – Das_Geek Nov 25 '19 at 14:33
  • you have answered linux command. but the question was asked for python. – Dipankar Nalui Mar 05 '20 at 10:41