我如何能得到一个特定的子字符串后的字符串?

例如,我想在“world”后面输入字符串

my_string="hello python world, I'm a beginner"

...在这种情况下是:“,我是初学者”)


当前回答

我很惊讶没人提到分区。

def substring_after(s, delim):
    return s.partition(delim)[2]

s1="hello python world, I'm a beginner"
substring_after(s1, "world")

# ", I'm a beginner"

恕我直言,这个解决方案比@arshajii的更具可读性。除此之外,我认为@arshajii的是最好的,因为它是最快的——它不会创建任何不必要的副本/子字符串。

其他回答

最简单的方法可能就是把你的目标单词分开

my_string="hello python world , i'm a beginner"
print(my_string.split("world",1)[1])

Split接受要拆分的单词(或字符),并可选地限制拆分的次数。

在这个例子中,对“world”进行分割,并将其限制为一次分割。

试试下面的方法:

import re

my_string="hello python world , i'm a beginner"
p = re.compile("world(.*)")
print(p.findall(my_string))

# [" , i'm a beginner "]
s1 = "hello python world , i'm a beginner"
s2 = "world"

print(s1[s1.index(s2) + len(s2):])

如果你想处理s2在s1中不存在的情况,那么使用s1.find(s2)而不是index。如果该调用的返回值是-1,则s2不在s1中。

如果你想使用regex来做这个,你可以简单地使用一个非捕获组,来获取单词“world”,然后捕获后面的所有东西,就像这样

(?:world).*

这里测试了示例字符串

在Python 3.9中,添加了一个新的removeprefix方法:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

文档:https://docs.python.org/3.9/library/stdtypes.html str.removeprefix 公告:https://docs.python.org/3.9/whatsnew/3.9.html