我如何能得到一个特定的子字符串后的字符串?
例如,我想在“world”后面输入字符串
my_string="hello python world, I'm a beginner"
...在这种情况下是:“,我是初学者”)
我如何能得到一个特定的子字符串后的字符串?
例如,我想在“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的是最好的,因为它是最快的——它不会创建任何不必要的副本/子字符串。
其他回答
这是一个老问题,但我面临着一个非常相同的场景,我需要分割字符串使用非军事化字“低”的问题对我来说是,我在相同的字符串字下面和更低。
我用re模块这样解出来的
import re
string = '...below...as higher prices mean lower demand to be expected. Generally, a high reading is seen as negative (or bearish), while a low reading is seen as positive (or bullish) for the Korean Won.'
# use re.split with regex to match the exact word
stringafterword = re.split('\\blow\\b',string)[-1]
print(stringafterword)
# ' reading is seen as positive (or bullish) for the Korean Won.'
# the generic code is:
re.split('\\bTHE_WORD_YOU_WANT\\b',string)[-1]
希望这能帮助到一些人!
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
试试下面的方法:
import re
my_string="hello python world , i'm a beginner"
p = re.compile("world(.*)")
print(p.findall(my_string))
# [" , i'm a beginner "]