获取特定子字符串后面的字符串如何在特定子字符串后获取字符串。例如,我想以后得到的字符串"world"中my_string="hello python world , i'm a beginner "
3 回答

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
最简单的方法可能只是拆分你的目标词
my_string="hello python world , i'm a beginner "print my_string.split("world",1)[1]
split将单词(或字符)拆分,并可选择限制拆分数。
在此示例中,拆分“世界”并将其限制为仅一个拆分。

烙印99
TA贡献1829条经验 获得超13个赞
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
。

德玛西亚99
TA贡献1770条经验 获得超3个赞
我很惊讶没有人提到过partition
。
def substring_after(s, delim): return s.partition(delim)[2]
恕我直言,这个解决方案比@ arshajii更具可读性。除此之外,我认为@ arshajii是最快的 - 它不会创建任何不必要的副本/子串。
添加回答
举报
0/150
提交
取消