开发者

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

开发者 https://www.devze.com 2022-12-26 12:34 出处:网络
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 remov

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 occur开发者_StackOverflow中文版rences of "word:".

Thanks! :-)


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.


[ chunk for chunk in line.split() if not chunk.endswith(":") ]

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


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(':'))
0

精彩评论

暂无评论...
验证码 换一张
取 消