0

I have a word like

fef2.  

I needed only "f2"(concatenation of 3rd and 4th character) from that word. How can i extract it from the word given using split. When i see the functionality of the split, it works only when there is a delimiter. How to split if there is no delimiter in the word?

Wooble
  • 87,717
  • 12
  • 108
  • 131
Justin Carrey
  • 3,563
  • 8
  • 32
  • 45

3 Answers3

6
>>> 'fef2.'[2:4]
'f2'

From The Python Tutorial:

Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.

>>> word
'HelpA'
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • dst = "ff02::ef12:2345:2345:f3f4" temp = dst.split(':')[-1:] temp2 = temp[2:4] print temp.....I should get an answer to this as f4 according to the solution. I am still getting f3f4 as output. i am using python 2.6. is this a problem of python? – Justin Carrey Nov 27 '12 at 17:57
  • @JustinCarrey `print temp2` – John Kugelman Nov 27 '12 at 18:12
1

You don't need split() for this:

s = 'fef2.'
print(s[2:4])

Here, 2 is the starting index and 4 is one past the ending index. Python uses zero-based indices, so the first character's index is zero.

The start:end construct is called a slice. You can read more about slicing here: Explain Python's slice notation

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I'd love to see this answer include a description of what a slice is in Python. http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation – bossylobster Nov 27 '12 at 17:49
  • @bossylobster: Good idea. Link added. – NPE Nov 27 '12 at 17:51
0

Use the substring 'fe' as the delimiter does the work.

'fef2'.split(sep = 'fe')

However, this approach can't deal with the dot at the end of the string.

sPaceVodka
  • 31
  • 2