如何在Python中用列表元素替换字符串中的指定占位符
解决Python中依次替换字符串占位符的问题
这里有两种适合新手的实现方式,都能完成你需要的依次替换需求:
方法1:利用字符串的replace和format方法
先把原字符串中的[word]占位符替换为format方法支持的{},再通过解包列表元素完成依次填充:
word_list = ['text', 'be', 'there'] text = "This is an example [word]. Normally there would [word] something important here but [word] isn't." # 替换占位符格式,再填充列表元素 formatted_text = text.replace('[word]', '{}').format(*word_list) print(formatted_text)
运行后会输出你需要的结果:
This is an example text. Normally there would be something important here but there isn't.
方法2:使用正则表达式配合迭代器
如果不想修改原字符串的占位符格式,可以用正则匹配[word],同时通过迭代器依次取出列表元素替换:
import re word_list = ['text', 'be', 'there'] text = "This is an example [word]. Normally there would [word] something important here but [word] isn't." # 将列表转为迭代器,每次匹配到占位符就取下一个元素 word_iterator = iter(word_list) result = re.sub(r'\[word\]', lambda match: next(word_iterator), text) print(result)
这个方法会直接匹配原字符串中的[word],逐个替换为列表里的元素,输出结果和方法1一致。
内容的提问来源于stack exchange,提问作者Bluffyyy
相关产品推荐
相关产品推荐

