jessyjack
jessyjack

Reputation: 35

python split string according to letter position in another string

Ok so lets say I have two strings.

the first string is a series of 44 o's with 6 random v's

the second string is a some text and is 44 characters in length

random_string = "bzpsvawxqpvjmldhnmvdseftystvfjimcrwoftvchmqlvwugcm"
some_text = "LoremIpsumDolourSitAmettyConssecteturAdipisc"

I am looking for a way to split the some_text string based on the v split of random_string.

random_string = "oooovooooovooooooovoooooooovoooooooooovooooovooooo"
splitted_string = random_string.split('v') 
print(splitted_string)
#['oooo', 'ooooo', 'ooooooo', 'oooooooo', 'oooooooooo', 'ooooo', 'ooooo']

but i would like to apply this split pattern to some_text to achieve

['Lore', 'mIpsu', 'mDolour', 'SitAmett', 'yConssecte', 'turAd', 'ipisc']

Upvotes: 0

Views: 139

Answers (2)

Giovanni Tardini
Giovanni Tardini

Reputation: 568

I found a solution, I hope it is general enough for you:

import re

random_string = "oooovooooovooooooovoooooooovoooooooooovooooovooooo"
some_text = "LoremIpsumDolourSitAmettyConssecteturAdipisc"

b = [m.start() for m in re.finditer('v', random_string)]
b = [0] + b + [len(b)]

c = [ some_text[b[j]:b[j+1]] for j in range(len(b)-1)]
print(c)

Upvotes: 0

Alexey S. Larionov
Alexey S. Larionov

Reputation: 7927

You can use string slices, based on lengths of the split random_string parts

text_split = []
current_i = 0
for random_substr in random_string.split('v'):
    text_substr = some_text[current_i:current_i+len(random_substr)]
    text_split.append(text_substr)
    current_i += len(random_substr)
print(text_split)

Upvotes: 1

Related Questions