说,如果我有一个像如何从Python中每个单词的右侧去除字符?
text='a!a b! c!!!'
文本我想要的结果是这样的:
text='a!a b c'
因此,如果每个词的结尾是,我想摆脱“!”它。如果有多个'!'在一个词的结尾,所有这些都将被淘汰。
说,如果我有一个像如何从Python中每个单词的右侧去除字符?
text='a!a b! c!!!'
文本我想要的结果是这样的:
text='a!a b c'
因此,如果每个词的结尾是,我想摆脱“!”它。如果有多个'!'在一个词的结尾,所有这些都将被淘汰。
发生作为替代分流/条途径
" ".join(x.rstrip("!") for x in text.split())
赢得”不能准确地保留空格,你可以使用正则表达式,如
re.sub(r"!+\B", "", text)
其中的所有感叹词都是空白的,而不是紧接着一个单词的开头。
您发布的正则表达式存在字符串问题,例如'a !! b'。 – Matt
你想要'\!+ \ B(?!\ S)'。 –
这里有一个非正则表达式,非分割为基础的方法:
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"
如果我必须摆脱报价(')和双引号(“),而不仅仅是(!)? –