我想知道如何从Python中的字符串中删除动态词。如何从Python中的字符串中删除以“:”结尾的所有单词?
它在单词的末尾总会有一个“:”,有时候在字符串中有多个。我想删除所有出现的“word:”。
谢谢! :-)
我想知道如何从Python中的字符串中删除动态词。如何从Python中的字符串中删除以“:”结尾的所有单词?
它在单词的末尾总会有一个“:”,有时候在字符串中有多个。我想删除所有出现的“word:”。
谢谢! :-)
使用正则表达式。
import re
blah = "word word: monty py: thon"
answer = re.sub(r'\w+:\s?','',blah)
print answer
这也将拉出冒号后的单个可选空间。
这消除其与结尾的所有词语 “:”:
def RemoveDynamicWords(s):
L = []
for word in s.split():
if not word.endswith(':'):
L.append(word)
return ' '.join(L)
print RemoveDynamicWords('word: blah')
或用生成器表达式:
print ' '.join(i for i in word.split(' ') if not i.endswith(':'))
@David:这不是一个生成器表达式,这是一个列表表达式 – 2010-04-07 01:04:24
感谢您的更正! – cryo 2010-04-07 03:05:09
[ chunk for chunk in line.split() if not chunk.endswith(":") ]
这将创建的列表。你可以在之后加入他们。
什么是“动态词”? – 2013-08-21 00:25:03