Python中如何正确替换字符串?

比如这样一段字符串
<meta name=“detectify-verification” content=“d0264f228155c7a1f72c3d91c17ce8fb” />
<meta name=“p:domain_verify” content=“b87e3b55b409494aab88c1610b05a5f0”/>
<meta name=“alexaVerifyID” content=“OFc8dmwZo7ttU4UCnDh1rKDtLlY” />
<meta name=“baidu-site-verification” content=“D00WizvYyr” />

content 里面的内容是随机的,如何把他们替换成
<meta name=“detectify-verification” content=“d0264f228155c7a1f72c3d91c17ce8fb.html” />
<meta name=“p:domain_verify” content=“b87e3b55b409494aab88c1610b05a5f0.html”/>
<meta name=“alexaVerifyID” content=“OFc8dmwZo7ttU4UCnDh1rKDtLlY.html” />
<meta name=“baidu-site-verification” content=“D00WizvYyr.html” />

我只懂得把 content 的内容提取出来,再 for 循环一个个替换,但是感觉有点麻烦,有没有办法不使用循环,直接用 replace 或者 re 搞定?
Python中如何正确替换字符串?


6 回复

过于基础了吧,建议百度,现在给你写了下次还要问


在Python里替换字符串,最直接的就是用 str.replace() 方法。这玩意儿是原地替换,返回一个新字符串,原来的不会变。

基本语法就长这样: new_string = old_string.replace(old_substring, new_substring, count)

  • old_substring:你想换掉的那部分。
  • new_substring:你想换成的新内容。
  • count(可选):指定替换几次,默认是全换。

举个例子,比如有个字符串 text = "Hello World, World is big."

text = "Hello World, World is big."
# 把所有的 "World" 换成 "Python"
new_text = text.replace("World", "Python")
print(new_text)  # 输出: Hello Python, Python is big.

# 只换第一个 "World"
new_text_once = text.replace("World", "Python", 1)
print(new_text_once)  # 输出: Hello Python, World is big.

如果你要搞更复杂的模式匹配,比如根据正则表达式来换,那就得上 re 模块里的 re.sub() 了。比如说,想把所有数字都换成井号 #

import re
text_with_numbers = "My number is 12345 and yours is 67890."
# 匹配所有数字(\d+),替换成 #
anonymized_text = re.sub(r'\d+', '#', text_with_numbers)
print(anonymized_text)  # 输出: My number is # and yours is #.

re.sub() 的格式是 re.sub(pattern, repl, string, count=0, flags=0),功能强大多了。

简单替换用 replace(),复杂规则用 re.sub()

同意#1
不就把
" />
替换成
.html" />
?

你不会从来没用过替换方法吧?

不就是 content=""里面的字符串+‘.html ’么😓



不是,感觉我问的方式有问题,这种问法的确一替换就好了,我再想想怎么问好

这。。。。。。建议多做一些处理字符串的练习

回到顶部