How can I delete everything in a string until characters (characters) are visible in Python

Say I have a string and I want to delete the rest of the string before or after viewing certain characters

For example, all my lines have an egg in them:

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

I want to receive:

"egg please"
"eggs are good"

as well as the same question, but how can I remove everything except the string before the characters?

+5
source share
4 answers

You can use a method str.findwith simple indexing:

>>> 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!
+14

str.join() str.partition():

''.join('have an egg please'.partition('egg')[1:])
+2

use regular expression to extract substring.

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)
+1
source
>>> s = "eggs are good"
>>> word = "eggs"
>>> if word in s:
        print s.split(word)[1]
are good
-1
source

Source: https://habr.com/ru/post/1611716/


All Articles