Ava
Ava

Reputation: 23

How to split string by list of Indexes python?

I have a list of indexes, like so:

[2, 6, 9]

And I would like to split a string In such a way that it would return a list of strings split at those indexes, i.e.:

"Hello there!" -> ["He", "llo ", "the", "re!"]

Upvotes: 1

Views: 1781

Answers (4)

Randy
Randy

Reputation: 14847

Here's a version using a list comprehension:

In [42]: s = "Hello there!"

In [43]: [s[v1:v2] for v1, v2 in zip([0]+l, l+[None])]
Out[43]: ['He', 'llo ', 'the', 're!']

Upvotes: 4

Aditya Sonawane
Aditya Sonawane

Reputation: 203

You can use this code and tempList gives you the output:

indexList=[2, 6, 9]
tempList=[]

inputString="Hello there!"
temp=0
tempString=""

for j in range(0, len(indexList), 1):
    for i in range(temp, indexList[j], 1):
        tempString=tempString+inputString[i]
    
    tempList.append(tempString)
    tempString=""
    temp=indexList[j]

for i in range(indexList[-1], len(inputString), 1):
    tempString=tempString+inputString[i]
tempList.append(tempString)
    
print(tempList)
    

Upvotes: 0

pakpe
pakpe

Reputation: 5479

You can do it by slicing. First you complete the list of indexes to include 0 and the beginning and the length of the phrase at the end. Then you iterate and slice between two adjacent indexes:

phrase = "Hello there!"
indexes = [2, 6, 9]
indexes.insert(0,0)
indexes.append(len(phrase))

lst = []
for i in range(1, len(indexes)):
    lst.append(phrase[indexes[i-1]:indexes[i]])
    
print(lst)

#['He', 'llo ', 'the', 're!']

Upvotes: 0

Vishal Singh
Vishal Singh

Reputation: 6234

mystring = "Hello there!"
indexes = [2, 6, 9]

start = 0
output = []

for end in indexes:
    output.append(mystring[start:end])
    start = end
output.append(mystring[end:])

print(output)

Output:

['He', 'llo ', 'the', 're!']

Upvotes: 0

Related Questions