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

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

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

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


当前回答

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

(?:world).*

这里测试了示例字符串

其他回答

我很惊讶没人提到分区。

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的是最好的,因为它是最快的——它不会创建任何不必要的副本/子字符串。

如果你想使用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

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中。

你可以使用名为substring的包。只需使用命令pip install substring进行安装。您可以通过只提到开始和结束字符/索引来获得子字符串。

例如:

import substring
s = substring.substringByChar("abcdefghijklmnop", startChar="d", endChar="n")
print(s)

输出:

# s = defghijklmn