查找子字符串并在其之前获取子字符串

时间:2020-07-07 10:03:30

标签: python

我是python的新手,并且有一个字符串,其中每个字符串都包含PR,如下所示

This is my PR and its related to me.
This is your PR and its related to you.

我想找到PR并在其前面获取字符串,所以我的输出如下:

This is my 
This is your

3 个答案:

答案 0 :(得分:2)

您可以尝试使用.split()方法。代码如下:

>>> 'This is my PR and its related to me.'.split(' PR ')[0]
'This is my'

答案 1 :(得分:0)

使用find函数查找`PR的索引,并将字符串切成该点。

s = 'This is my PR and its related to me.'
pos = s.find('PR')
print(s[:pos])

答案 2 :(得分:-1)

重新导入

字符串= re.findall(r“ ^ \ w +” PR) 打印(字符串)