gpt4 book ai didi

python - 在 Python 中看到字符之前,如何删除字符串中的所有内容

转载 作者:太空狗 更新时间:2023-10-30 00:24:08 26 4
gpt4 key购买 nike

假设我有一个字符串,我想在看到某些字符之前或之后删除该字符串的其余部分

例如,我所有的字符串中都有“egg”:

"have an egg please"
"my eggs are good"

我想得到:

"egg please"
"eggs are good"

还有同样的问题,但如何删除字符前面的字符串以外的所有内容?

最佳答案

您可以使用带有简单索引的str.find 方法:

>>> s="have an egg please"
>>> s[s.find('egg'):]
'egg please'

请注意,str.find 将在未找到子字符串时返回 -1 并将返回字符串的最后一个字符。因此,如果您没有找到确保您的字符串始终包含子字符串,您最好在使用它之前检查 str.find 的值。

>>> def slicer(my_str,sub):
... index=my_str.find(sub)
... if index !=-1 :
... return my_str[index:]
... else :
... raise Exception('Sub string not found!')
...
>>>
>>> slicer(s,'egg')
'egg please'
>>> slicer(s,'apple')
Sub string not found!

关于python - 在 Python 中看到字符之前,如何删除字符串中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com