Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all words that end in ":" from a string in Python?

Tags:

python

regex

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! :-)

like image 894
veb Avatar asked Apr 07 '10 00:04

veb


1 Answers

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.

like image 139
Seth Johnson Avatar answered Nov 04 '22 04:11

Seth Johnson