简体   繁体   中英

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

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.

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM