-3

I have a string in the below format:

00:aa:bb:cc:dd:ee  

I need to split it and output only first 3 fields, i.e. 00:aa:bb. I am using

s.split(':')[1:3]  

in my program to do the job, but its not helping. Is it the right way to do this?

Justin Carrey
  • 3,563
  • 8
  • 32
  • 45

2 Answers2

5

Almost: Python is 0-indexed (counts from 0):

>>> s = '00:aa:bb:cc:dd:ee'
>>> s.split(":")
['00', 'aa', 'bb', 'cc', 'dd', 'ee']
>>> s.split(":")[0:3]
['00', 'aa', 'bb']
>>> s.split(":")[:3]
['00', 'aa', 'bb']

And you could recombine them:

>>> ':'.join(s.split(":")[:3])
'00:aa:bb'

You can see this question for a brief review of how Python slicing works, if that's the issue.

Community
  • 1
  • 1
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    Since he only needs the first 3, splitting the rest is a waste. Could just do `':'.join(s.split(':', 3)[:3])` so the interpreter will drop out of the parse after getting the tokens he needs and no more. – Silas Ray Aug 30 '12 at 20:59
  • @sr2222: yep, you're right. `timeit` difference: 1090 ns vs 931 ns. I don't think I'll worry too much. :^) – DSM Aug 30 '12 at 21:06
  • Depends how many strings he has, but true. :) Also, if all the strings look just like the one shown (2 char sequences delimited by colons), just doing `s[:8]` would be even better. – Silas Ray Aug 30 '12 at 21:13
1

What do you mean it's not helping? Is it because the result is a list? To turn it back to a string try:

':'.join(s.split(':')[0:3])

Also note the zero-index.

Neal
  • 6,722
  • 4
  • 38
  • 31