I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?
我只想替换字符串中正则表达式的第一次出现。有方便的方法吗?
2 个解决方案
#1
36
re.sub()
has a count
parameter that indicates how many substitutions to perform. You can just set that to 1:
res .sub()有一个count参数,指示要执行多少替换。你可以把它设为1:
>>> s = "foo foo foofoo foo"
>>> re.sub("foo", "bar", s, 1)
'bar foo foofoo foo'
>>> s = "baz baz foo baz foo baz"
>>> re.sub("foo", "bar", s, 1)
'baz baz bar baz foo baz'
Edit: And a version with a compiled SRE object:
编辑:和一个带有编译SRE对象的版本:
>>> s = "baz baz foo baz foo baz"
>>> r = re.compile("foo")
>>> r.sub("bar", s, 1)
'baz baz bar baz foo baz'
#2
5
Specify the count
argument in re.sub(pattern, repl, string[, count, flags])
在re.sub中指定count参数(模式、repl、string[、count、flags])
The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced.
可选参数计数是要替换的模式出现的最大数量;count必须是非负整数。如果省略或为零,则将替换所有出现的情况。
#1
36
re.sub()
has a count
parameter that indicates how many substitutions to perform. You can just set that to 1:
res .sub()有一个count参数,指示要执行多少替换。你可以把它设为1:
>>> s = "foo foo foofoo foo"
>>> re.sub("foo", "bar", s, 1)
'bar foo foofoo foo'
>>> s = "baz baz foo baz foo baz"
>>> re.sub("foo", "bar", s, 1)
'baz baz bar baz foo baz'
Edit: And a version with a compiled SRE object:
编辑:和一个带有编译SRE对象的版本:
>>> s = "baz baz foo baz foo baz"
>>> r = re.compile("foo")
>>> r.sub("bar", s, 1)
'baz baz bar baz foo baz'
#2
5
Specify the count
argument in re.sub(pattern, repl, string[, count, flags])
在re.sub中指定count参数(模式、repl、string[、count、flags])
The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced.
可选参数计数是要替换的模式出现的最大数量;count必须是非负整数。如果省略或为零,则将替换所有出现的情况。