zhuyxn
zhuyxn

Reputation: 7091

Removing first appearance of word from a string?

I'm not familiar with regex, and it would be great if someone giving a solution using regex could explain their syntax so I can apply it to future situations.

I have a string (ie. 'Description: Mary had a little lamb'), and I would like to remove 'Description: ' such that the string would read 'Mary had a little lamb,' but only the first instance, such that if the string was 'Description: Description', the new string would be 'Description.'

Any ideas? Thanks!

Upvotes: 30

Views: 74127

Answers (4)

Walid
Walid

Reputation: 728

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'

Upvotes: 5

mhawke
mhawke

Reputation: 87134

This regex will work for any "word", not just "Description: "

>>> import re
>>> s = 'Blah: words words more words'
>>> print re.sub(r'^\S*\s', '', s)
words words more words
>>> 

Upvotes: 1

Josiah
Josiah

Reputation: 3326

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: '

Upvotes: 61

jamylak
jamylak

Reputation: 133744

Using regex just specify the count paramter as 1 in re.sub. Although it seems like regex is not needed in this case.

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

Upvotes: 0

Related Questions