首页 > 解决方案 > Python如何查找和替换未知部分或字符串

问题描述

假设我有一个字符串,我知道格式,但里面有变量,我怎样才能删除格式?前任:

s = """
<%Hello%>
<%foo%>
<%Example%>
<no
>%change
here%>
"""
print(s.replace("<%*%>", "&it works&"))

输出:

>   &it works&
    &it works&
    &it works&
    <no
    >%change
    here%>

标签: regexpython-3.x

解决方案


利用re.sub

前任:

import re

s = """
<%Hello%>
<%foo%>
<%Example%>
<no
>%change
here%>
"""
print(re.sub("<%(.*?)%>", "&it works&", s))

输出:

&it works&
&it works&
&it works&
<no
>%change
here%>

推荐阅读