Removing first appearance of word from a string?

You can do it without regex, using the replace function by setting the count arg to 1:

>>> string = 'Description: Mary had a little lamb Description'
>>> string.replace('Description', '', 1)
'Mary had a little lamb Description'

Python's str.replace has a max replace argument. So, in your case, do this:

>>>mystring = "Description: Mary had a little lamb Description: "
>>>print mystring.replace("Description: ","",1)

"Mary had a little lamb Description: "

Using regex is basically exactly the same. First, get your regex:

"Description: "

Since Python is pretty nice about regexes, it's just the string you want to remove in this case. With that, you want to use it in re.sub, which also has a count variable:

>>>import re
>>>re.sub("Description: ","",mystring,count=1)
'Mary had a little lamb Description: '

Tags:

Python

Regex