【发布时间】:2016-11-18 07:43:47
【问题描述】:
我想在字符串中获得前后匹配。
例如,使用以下字符串:
"Hello I am Jim!"
搜索字符串为:"I am",搜索字符串之前的匹配项应为:"Hello",之后的匹配项应为:"Jim!"。
我怎样才能做到这一点?
【问题讨论】:
标签: python string python-2.7 python-3.x
我想在字符串中获得前后匹配。
例如,使用以下字符串:
"Hello I am Jim!"
搜索字符串为:"I am",搜索字符串之前的匹配项应为:"Hello",之后的匹配项应为:"Jim!"。
我怎样才能做到这一点?
【问题讨论】:
标签: python string python-2.7 python-3.x
使用str.partition 正是这样做的:
S.rpartition(sep) -> (head, sep, tail)在
S中搜索分隔符sep,从S的末尾开始,返回它之前的部分、分隔符本身和它之后的部分。
所以,使用您的示例字符串:
before, search_str, after = "Hello I am Jim!".partition("I am ")
现在before、search_str 和after 是:
>>> print(before)
Hello
>>> print(search_str)
I am
>>> print(after)
Jim!
str.partition 还为您抓取 分隔符 作为返回元组中的中间元素。如果您不需要,str.split(separator) 就足够了。
【讨论】:
你也可以使用split()
>>> before, after = "Hello I am Jim!".split("I am")
>>> before
'Hello '
>>> after
' Jim!'
【讨论】:
Answer 是一个很好的申诉方式,但是你也可以使用 python 字符串操作 find 最基本的操作来获得相同的点。
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 !
在多种方式中实现,然后选择最简单的方式
【讨论】:
这是另一种方式:
>>> import re
>>> str1 = "Hello I am Jim!"
>>> before, after = re.split(" I am ", str1)
>>> before
'Hello'
>>> after
'Jim!'
【讨论】: