Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the first occurrence of a regular expression in Python?

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

like image 970
girish Avatar asked Oct 17 '10 01:10

girish


People also ask

How do you replace the first part of a string in Python?

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.

How do you replace all occurrences of a regex pattern in a string Python?

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.

How do you replace a regular expression in Python?

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.

How do I change occurrences in Python?

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.


1 Answers

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' 
like image 85
eldarerathis Avatar answered Oct 19 '22 16:10

eldarerathis