简体   繁体   English

如何在字符串中获得前后匹配?

[英]How can I get a after and before match in a string?

I want to get an after and before match in a string. 我想在字符串中获得匹配后和匹配前。

For example, using the following string: 例如,使用以下字符串:

"Hello I am Jim!"

with the search string being: "I am" , the match before the search string should be: "Hello" and the match after should be: "Jim!" 搜索字符串为"I am" ,则搜索字符串前的匹配项应为: "Hello" ,而之后的匹配项应为: "Jim!" .

How can I achieve this? 我该如何实现?

Use str.partition which does exactly this: 使用str.partition可以做到这一点:

S.rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S , starting at the end of S , and return the part before it, the separator itself, and the part after it. 搜索分隔sepS开始,结束S ,和之前返还一部分,该分离器本身,而其后的部分。

So, using your example string: 因此,使用示例字符串:

before, search_str, after = "Hello I am Jim!".partition("I am ")

Now before , search_str and after are: 现在, before search_strafter before是:

>>> print(before)
Hello 
>>> print(search_str)
I am
>>> print(after)
Jim!

str.partition also grabs the separator for you as the middle element in the returned tuple. str.partition还会为您获取分隔符 ,作为返回的元组中的中间元素。 If you don't require that, str.split(separator) suffices. 如果您不需要这样做,则str.split(separator)就足够了。

You can also use split() 您也可以使用split()

>>> before, after = "Hello I am Jim!".split("I am")
>>> before
'Hello '
>>> after
' Jim!'

Answer is a good way to appeal, but you can also use the python string operation find the most basic operation to get the same point. 回答是一个吸引人的好方法,但是您也可以使用python字符串操作找到最基本的操作来获得相同的观点。

s = "Hello I am Jim!"
print s.find('I am')
for i in range(s.find('I am')):
    print s[i],
for i in range(s.find('I am')+len('I am'),len(s)):
    print s[i],

python team.py 
6
H e l l o     J i m !

In a variety of ways to achieve, then choose the most simple approach 以多种方式实现,然后选择最简单的方法

Here is the another way: 这是另一种方式:

>>> import re
>>> str1 = "Hello I am Jim!"
>>> before, after = re.split(" I am ", str1)
>>> before
'Hello'
>>> after
'Jim!'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM