Reputation: 567
I have a string and list of indexes. I would like to extract characters from string at the positions indicated in the list to make a substring.
For example:
str = "Hello Stack Overflow"
lOfIndexes = [1,3,6]
I would like to get elS
How can I do this?
Upvotes: 0
Views: 469
Reputation: 6597
This is the perfect use for operator.itemgetter()
:
from operator import itemgetter
s = 'Hello Stack Overflow'
print ''.join(itemgetter(1, 3, 6)(s))
# OUT: 'elS'
Upvotes: 2
Reputation: 1908
Here you go:
some_string = "hello world"
indicies = [1,3,2]
output = []
for i in indicies:
output.append(some_string[i])
print ''.join(output)
Upvotes: 1
Reputation: 9884
There's no builtin function to do this, but it's simple enough with list comprehension.
>>> ''.join(str[i] for i in lOfIndexes)
>>> 'elS'
Upvotes: 6