import re
example = "gz15gr123da1az4gr1sd23f168zgre4r6z"
re.sub("(\d)gr", r"\1", example)
输出
gz15123da1az41sd23f168zgre4r6z
解释
re.sub 函数采用三个参数:第一个参数是模式,第二个参数是替换,最后一个参数是字符串本身。 (\d)gr 选择包含数字后跟 gr 的部分,然后将其替换为数字 (\d) 本身(删除 gr代码>部分)。
If I understand your question correctly, what you need is regex:
import re
example = "gz15gr123da1az4gr1sd23f168zgre4r6z"
re.sub("(\d)gr", r"\1", example)
Output
gz15123da1az41sd23f168zgre4r6z
Explnatation
The re.sub function takes three arguments: the first argument is a patter, the second one the replacement, and the last of is the string itself. (\d)gr selects the parts that contain a number followed by gr, then replaces it with the number (\d) itself(removing the gr part).
发布评论
评论(1)
如果我正确理解你的问题,你需要的是正则表达式:
输出
解释
re.sub
函数采用三个参数:第一个参数是模式,第二个参数是替换,最后一个参数是字符串本身。(\d)gr
选择包含数字后跟gr
的部分,然后将其替换为数字 (\d) 本身(删除gr
代码>部分)。If I understand your question correctly, what you need is regex:
Output
Explnatation
The
re.sub
function takes three arguments: the first argument is a patter, the second one the replacement, and the last of is the string itself.(\d)gr
selects the parts that contain a number followed bygr
, then replaces it with the number (\d) itself(removing thegr
part).