tags:

views:

81

answers:

3

Hi,

I'm wondering how to remove a dynamic word from a string within Python.

It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:".

Thanks! :-)

+3  A: 

Use regular expressions.

import re
blah = "word word: monty py: thon"
answer = re.sub(r'\w+:\s?','',blah)
print answer

This will also pull out a single optional space after the colon.

Seth Johnson
Thank you! The Python regexp docs is quite intimidating :(
veb
@veb A less intimidating intro to python regular expressions: http://www.amk.ca/python/howto/regex/
Jacinda S
@veb: welcome to SO. If a posted answer is what you're looking for, press the checkmark icon to "accept" it.
Seth Johnson
It told me to wait 7 minutes. So I'm waiting. heh
veb
Ahh okay. Didn't know that limitation; it must be new. Thanks!
Seth Johnson
A: 

This removes all words which end with a ":":

def RemoveDynamicWords(s):
    L = []
    for word in s.split():
        if not word.endswith(':'):
            L.append(word)
    return ' '.join(L)
print RemoveDynamicWords('word: blah')

or use a generator expression:

print ' '.join(i for i in word.split(' ') if not i.endswith(':'))
David Morrissey
@David: that's not a generator expression, that's a list expression.
Seth Johnson
thanks for the correction!
David Morrissey
A: 
[ chunk for chunk in line.split() if not chunk.endswith(":") ]

this will create a list. you can join them up afterwards.

ghostdog74