boo*_*erz 6 python string python-2.7 python-3.x
假设我有一个字符串,我想在看到某些字符之前或之后删除其余的字符串
例如,我的所有字符串都包含'egg':
"have an egg please"
"my eggs are good"
Run Code Online (Sandbox Code Playgroud)
我想得到:
"egg please"
"eggs are good"
Run Code Online (Sandbox Code Playgroud)
还有同样的问题,但我怎样才能删除除字符前面的字符串之外的所有字符串?
Kas*_*mvd 16
您可以使用str.find
简单索引的方法:
>>> s="have an egg please"
>>> s[s.find('egg'):]
'egg please'
Run Code Online (Sandbox Code Playgroud)
请注意,str.find
将返回-1
如果没有找到子字符串,将返回你string.So的最后一个字符,如果你不能确定你总是字符串包含子字符串您更好地检查的价值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!
Run Code Online (Sandbox Code Playgroud)
string = 'Stack Overflow'
index = string.find('Over') #stores the index of a substring or char
string[:index] #returns the chars before the seen char or substring
Run Code Online (Sandbox Code Playgroud)
因此,输出将是
'Stack '
Run Code Online (Sandbox Code Playgroud)
和
string[index:]
Run Code Online (Sandbox Code Playgroud)
会给
'Overflow'
Run Code Online (Sandbox Code Playgroud)