I want to insert a small str into a larger one in the most pythonic way.
Maybe I missed a useful str method or function ? The function that insert the small str into the larger one is insert_tag
.
I have tried something with reduce but it didn't work and it was too complex.
Code:
from random import choice, randrange
from typing import List
def insert_tag(text: str, offsets: List[int], tags: List[str]) -> str:
text: str = text
for offset, tag in zip(offsets, tags):
# text = f'{text[:offset]}{tag}{text[offset:]}' # solution 1
text = text[:offset] + tag + text[offset:] # solution 2
return text
if __name__ == '__main__':
tag_nbr = 30
# Text example
base_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' \
'eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ' \
'enim ad minim veniam, quis nostrud exercitation ullamco laboris ' \
'nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ' \
'in reprehenderit in voluptate velit esse cillum dolore eu fugiat ' \
'nulla pariatur. Excepteur sint occaecat cupidatat non proident, ' \
'sunt in culpa qui officia deserunt mollit anim id est laborum.' \
.replace(',', '').replace('.', '')
# Random list of tag only for testing purpose
tag_li: List[str] = [f'<{choice(base_text.split())}>' for _ in range(tag_nbr)]
# Ordered list of random offset only for testing purpose
offset_li: List[int] = [randrange(len(base_text)) for _ in range(tag_nbr)]
offset_li.sort(reverse=True)
# Debug
print(tag_li, offset_li, sep='\n')
# Review
new_text: str = insert_tag(base_text, offset_li, tag_li)
# End Review
# Debug
print(new_text)
Output:
"Lorem ips<consectetur>u<Lorem>m dolo<Lorem>r sit amet consecte<Lorem>tur <nostrud>adipiscing eli<aute>t sed d<anim>o eiusmod tempo<voluptate>r <exercitation>incid<anim>i<non>dunt ut l<quis>abor<do>e et dol<reprehenderit>ore magna aliqua Ut enim ad minim veniam quis nostrud exercitatio<est>n ullamco laboris nisi ut aliquip ex<nulla> ea <consectetur>commodo consequat Duis aute irure dolor in repreh<deserunt>enderit in voluptate vel<sint>it esse cillum dolore eu f<qui>ugiat nulla pariatur <magna>Excepteur sin<ex>t occaecat cup<labore>i<ut>datat non proident sun<est>t<in> in cul<fugiat>pa qui officia<enim> deserunt mollit anim i<in><anim>d est laborum"
PS: The rest of the code is not my primary concern, but if it can be improved, tell me, thanks.
Do not add an improved version of the code after receiving an answer. Including revised versions of the code makes the question confusing, especially if someone later reviews the newer code.
I didn't see that, thank you \$\endgroup\$