2013-04-16 47 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" 
相關問題