tags:

views:

114

answers:

6

How to extract substrings from a string at specified positions For e.g.: ‘ABCDEFGHIJKLM’. I have To extract the substring from 3 to 6 and 8 to 10.

Required output: DEFG, IJK

Thanks in advance.

+2  A: 
s = 'ABCDEFGHIJKLM'
print s[3:7]
print s[8:11]
shylent
+3  A: 
>>> 'ABCDEFGHIJKLM'[3:7]
'DEFG'
>>> 'ABCDEFGHIJKLM'[8:11]
'IJK'

You might want to read a tutorial or beginners book.

Lennart Regebro
+3  A: 

Look into Python's concept called sequence slicing!

mjv
+8  A: 

Here you go

myString = 'ABCDEFGHIJKLM'
first = myString[3:7] # => DEFG
second = myString[8:11] # => IJK

In the slicing syntax, the first number is inclusive and the second is excluded.

You can read more about String slicing from python docs

Shrikant Sharat
+3  A: 
a = "ABCDEFGHIJKLM"
print a[3:7], a[8:11]

--> DEFG IJK

luc
A: 

In alternative you can use operator.itemgetter:

>>> import operator
>>> s = 'ABCDEFGHIJKLM'
>>> f = operator.itemgetter(3,4,5,6,7,8,9,10,11)
>>> f(s)
('D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')
dalloliogm
`operator.itemgetter(slice(3, 7), slice(8, 11))('ABCDEFGHIJKLM') == ('DEFG', 'IJK')`
nosklo