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.
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.
>>> 'ABCDEFGHIJKLM'[3:7]
'DEFG'
>>> 'ABCDEFGHIJKLM'[8:11]
'IJK'
You might want to read a tutorial or beginners book.
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
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')