这和下面的问题有关-Searching for Unicode characters in Python
我有这样的绳子-
sentence = 'AASFG BBBSDC FEKGG SDFGF'
我把它分开,得到了下面这样的单词列表-
^{pr2}$我用下面的代码搜索一个单词的一部分,然后得到整个单词-
[word for word in sentence.split() if word.endswith("GG")]
它返回['FEKGG']
现在我要找出这个词的前后。在
例如,当我搜索“GG”时,它返回['FEKGG']
。它也应该能够
behind = 'BBBSDC'
infront = 'SDFGF'
这是一种方法。如果“GG”这个词在句子的开头或结尾,前面和后面的元素将是
None
。在Using this generator:
如果您有以下字符串(从原始值编辑):
这将返回:
^{pr2}$有一种可能:
您可能需要注意边缘情况,例如
"…GG"
没有出现、出现不止一次,或者是第一个和/或最后一个单词。按照目前的情况,任何一种情况都会引发一种例外,这很可能是正确的行为。在使用regex的完全不同的解决方案首先避免了将字符串拆分为数组:
^{pr2}$相关问题 更多 >
编程相关推荐