How Do I Replace Words In a String With Items In a List In Python

Question:

I have a list of words and a string with spaces to put the words in. I need to be able to distribute the items from the list into the spots in the string.

Example:

list = ['text', 'be', 'there']

text = "This is an example [word]. Normally there would [word] something important here but [word] isn't."

The output would be:

"This is an example text. Normally there would be something important here but there isn't."

I would need the parts with ‘[word]’ to be replaced with an item from the list.
I am pretty new to python so forgive me if the answer is obvious.

Asked By: Bluffyyy

||

Answers:

We can use re.sub along with a callback function:

list = ['text', 'be', 'there']
text = "This is an example [word]. Normally there would [word] something important here but [word] isn't."
output = re.sub(r'[word]', list.pop(0), text)
print(output)

This prints:

This is an example text. Normally there would be something important here but there isn't.

The strategy here is that for each [word] match, we call pop(0) on the list of replacements. This returns the first element in that list, while also removing it and queueing up the next replacement.

Answered By: Tim Biegeleisen

Try re.sub with custom function:

import re

lst = ["text", "be", "there"]
text = "This is an example [word]. Normally there would [word] something important here but [word] isn't."


text = re.sub(r"[word]", lambda _, i=iter(lst): next(i), text)
print(text)

Prints:

This is an example text. Normally there would be something important here but there isn't.
Answered By: Andrej Kesely

They advise using the re library here, however, I think it’s easier, easier and better to use simple text.format() formatting

Code example:

list_of_words = ['text', 'be', 'there']

text = "This is an example {}. Normally there would {} something important here but {} isn't.".format(*list_of_words)

The output will look like this:

This is an example text. Normally there would be something important here but there isn't.
Answered By: Dmitrii Gavrilov

You can split the input string by [word], zip the resulting list with the input list, flatten the pairs and join them for output:

words = ['text', 'be', 'there']
text = "This is an example [word]. Normally there would [word] something important here but [word] isn't."

print(''.join(w for p in zip(text.split('[word]'), (*words, '')) for w in p))

Demo: https://ideone.com/yMdSOA

Answered By: blhsing
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.