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

Time:09-15

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.

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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.
  • Related