58

I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?

2 Answers 2

79

re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 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:

>>> s = "baz baz foo baz foo baz"
>>> r = re.compile("foo")
>>> r.sub("bar", s, 1)
'baz baz bar baz foo baz'
Sign up to request clarification or add additional context in comments.

Comments

17

Specify the count argument in re.sub(pattern, 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.