The sample string and the given range of index numbers of a character can be seen below:
a_str = 'Iamgoingtoschool'
num_index = ['1','3','8','10','16',...]
As the position of a character ('|'
) should be assigned as index number of the list(num_index
), the outcome should be like this:
get_result = 'I|am|going|to|school|'
The attempt is in below:
for i in num_index:
get_res = a_str[:i]+'|'+a_str[i:]
First of all, your values in num_index
should not be strings. They should be integers.
num_index = [int(n) for n in num_index]
After that, you're completely overwriting get_result
on each iteration of your loop. Instead, strive for something more like this:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
get_result = a_str[:num_index[0]] # Start with the first chunk of `a_str`
for a, b in pairwise(num_index):
get_result += '|' + a_str[a:b]
get_result += '|' + a_str[num_index[-1]:] # Attach the last part.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments