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

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

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

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


当前回答

在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 "]

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

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

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

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

这是一个老问题,但我面临着一个非常相同的场景,我需要分割字符串使用非军事化字“低”的问题对我来说是,我在相同的字符串字下面和更低。

我用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]

希望这能帮助到一些人!

在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

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

(?:world).*

这里测试了示例字符串