Extracting substrings at specified positions
How to extract substrings from a string at specified positions For e.g.: ‘ABCDEFGHI开发者_如何学PythonJKLM’. I have To extract the substring from 3 to 6 and 8 to 10.
Required output: DEFG, IJK
Thanks in advance.
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
Look into Python's concept called sequence slicing!
a = "ABCDEFGHIJKLM"
print a[3:7], a[8:11]
--> DEFG IJK
s = 'ABCDEFGHIJKLM'
print s[3:7]
print s[8:11]
>>> 'ABCDEFGHIJKLM'[3:7]
'DEFG'
>>> 'ABCDEFGHIJKLM'[8:11]
'IJK'
You might want to read a tutorial or beginners book.
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')
精彩评论