如何多次向字符串添加内容?
import re
content = 'This is random text. I want to insert HELLO here --> "" and here too --> ""'
for text in re.finditer('""', content):
start_index = text.start() + 1
end_index = text.end() - 1
content = content[:start_index] + 'HELLO' + content[end_index:]
print(content)
不幸的是,上面的代码给了我以下内容:
This is random text. I want to insert HELLO here --> "HELLO" and here too HELLO--> ""
答案 0 :(得分:1)
content.replace('""', '"HELLO"')
怎么样?
答案 1 :(得分:1)
这就是您想要的:
string = ' geeks for geeks geeks geeks geeks'
# Prints the string by replacing geeks by Geeks
print(string.replace("geeks", '"Geeks"'))
结果是:
"Geeks" for "Geeks" "Geeks" "Geeks" "Geeks"