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

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

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

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


当前回答

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

例如:

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

输出:

# s = defghijklmn

其他回答

我很惊讶没人提到分区。

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

在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

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

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

希望这能帮助到一些人!

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

例如:

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

输出:

# s = defghijklmn

试试下面的方法:

import re

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

# [" , i'm a beginner "]