Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中看到一个或多个字符之前,如何删除字符串中的所有内容_Python_Python 3.x_String_Python 2.7 - Fatal编程技术网

在Python中看到一个或多个字符之前,如何删除字符串中的所有内容

在Python中看到一个或多个字符之前,如何删除字符串中的所有内容,python,python-3.x,string,python-2.7,Python,Python 3.x,String,Python 2.7,假设我有一个字符串,我想在看到某些字符之前或之后删除该字符串的其余部分 例如,我所有的字符串中都有“egg”: "have an egg please" "my eggs are good" 我想得到: "egg please" "eggs are good" 还有同样的问题,但如何删除字符前面的字符串以外的所有字符?您可以使用str.find方法,并使用一个简单的索引: >>> s="have an egg please" >>> s[s.find('e

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

例如,我所有的字符串中都有“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!

使用正则表达式获取子字符串

import re
def slice(str, startWith):
    m = re.search(r'%s.*' % startWith,str) # to match pattern starts with `startWith`
    if not m: return ""#there is no proper pattern, m is None
    else: return m.group(0)
您可以使用
str.join()
str.partition()

string='Stack Overflow'
index=string.find('Over')#存储子字符串或字符的索引
字符串[:index]#返回所看到的字符或子字符串之前的字符
因此,输出将是

'Stack '

将给予

'Overflow'

值得注意的是——如果未找到子字符串,
find
将返回
-1
,因此将输出主字符串的最后一个字符(如上面的
e
)。另一种选择是将
find
替换为
index
,这类似于
find
,但如果未找到子字符串,则会引发
ValueError
,然后相应地处理异常。@DrearBirateShawn确实用额外的信息更新了答案。请注意。它不应该返回错误消息而不是打印它吗?谢谢你,这是我使用的方法,它现在正在工作。我所做的唯一区别是替换了“未找到子字符串!”使用pass。这不会打印拆分器参数。您可以使用[:index]保留第一部分,而OP希望保留除以下内容以外的所有内容。使用索引切换冒号与问题一致,感谢您指出这一点。我会编辑它。
'Stack '
string[index:]
'Overflow'