假设我有一个像这样的字符串:
*question: What percentage is the correct answer?
33%
15%
2%
25%
我需要在问题行之后添加一个shuffle
命令:
*question: What percentage is the correct answer?
*shuffle
33%
15%
2%
25%
这样做的最佳方法是什么?我可以使用任何记事本编辑器或 Python。
我想我可以使用以下正则表达式来捕获第一行的所有内容:^(\*question).*
,但我不确定如何添加 *shuffle
语法直接位于换行符之后。
最佳答案
您可以使用
import re
data = """
*question: What percentage is the correct answer?
33%
15%
2%
25%
"""
rx = re.compile(r'(\*question.+)', re.M)
data = rx.sub(r'\1\n *shuffle', data)
print(data)
哪个产量
*question: What percentage is the correct answer?
*shuffle
33%
15%
2%
25%
关于python - 匹配包含特定文本的整行,并在换行符后添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631737/