2013-04-16 46 views
3

说,如果我有一个像如何从Python中每个单词的右侧去除字符?

text='a!a b! c!!!' 

文本我想要的结果是这样的:

text='a!a b c' 

因此,如果每个词的结尾是,我想摆脱“!”它。如果有多个'!'在一个词的结尾,所有这些都将被淘汰。

+0

如果我必须摆脱报价(')和双引号(“),而不仅仅是(!)? –

回答

4
print " ".join(word.rstrip("!") for word in text.split()) 
+1

如果文本包含选项卡或不同的空格,这可能会返回一个不同的字符串。 –

+1

简单解决方法是使用'text.split('')' – jamylak

+0

@ jamylak,不会在可能位于字符串中的选项卡上分割 – Matt

1
import re 
>>> testWord = 'a!a b! c!!!' 
>>> re.sub(r'(!+)(?=\s|$)', '', testWord) 
'a!a b c' 

这保留任何多余的空格,你可能在你的字符串不与str.split()

+0

为什么使用'\ Z'而不是'$'? – jamylak

+0

@jamylak因为某些原因,我忘记了$,我更新了它 – Matt

3

发生作为替代分流/条途径

" ".join(x.rstrip("!") for x in text.split()) 

赢得”不能准确地保留空格,你可以使用正则表达式,如

re.sub(r"!+\B", "", text) 

其中的所有感叹词都是空白的,而不是紧接着一个单词的开头。

+0

您发布的正则表达式存在字符串问题,例如'a !! b'。 – Matt

+0

你想要'\!+ \ B(?!\ S)'。 –

0

这里有一个非正则表达式,非分割为基础的方法:

from itertools import groupby 

def word_rstrip(s, to_rstrip): 
    words = (''.join(g) for k,g in groupby(s, str.isspace)) 
    new_words = (w.rstrip(to_strip) for w in words) 
    return ''.join(new_words) 

这工作首先利用itertools.groupby组合到一起的连续字符根据它们是否是空白:

>>> s = "a!a b! c!!" 
>>> [''.join(g) for k,g in groupby(s, str.isspace)] 
['a!a', ' ', 'b!', ' ', 'c!!'] 

实际上,这就像一个保留空白的.split()。一旦我们有了这个,我们可以使用rstrip,因为我们总是会,然后再重组:

>>> [''.join(g).rstrip("!") for k,g in groupby(s, str.isspace)] 
['a!a', ' ', 'b', ' ', 'c'] 
>>> ''.join(''.join(g).rstrip("!") for k,g in groupby(s, str.isspace)) 
'a!a b c' 

我们还可以通过任何我们喜欢:

>>> word_rstrip("a!! this_apostrophe_won't_vanish these_ones_will'''", "!'") 
"a this_apostrophe_won't_vanish these_ones_will" 
相关问题