user3259937
user3259937

Reputation: 567

Extracting characters from a string using a list of indexes

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

Answers (3)

pzp
pzp

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

jonhurlock
jonhurlock

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

Jayanth Koushik
Jayanth Koushik

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

Related Questions