I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?
Use Python built-in replace() function to replace the first character in the string. The str. replace takes 3 parameters old, new, and count (optional). Where count indicates the number of times you want to replace the old substring with the new substring.
sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.
To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.
Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With