简体   繁体   中英

How can I remove everything in a string until a character(s) are seen in Python

Say I have a string and I want to remove the rest of the string before or after certain characters are seen

For example, all my strings have 'egg' in them:

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

I want to get:

"egg please"
"eggs are good"

and also the same question but how can I delete all but the string in front of the characters?

You can use str.find method with a simple indexing :

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

Note that str.find will returns -1 if it doesn't find the sub string and will returns the last character of your string.So if you are not sure that always your string is contain the sub string you better to check the value of str.find before using it.

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

Hence, the output will be

'Stack '

and

string[index:]

will give

'Overflow'

use regular expression to fetch the sub string.

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()

''.join('have an egg please'.partition('egg')[1:])
>>> s = "eggs are good"
>>> word = "eggs"
>>> if word in s:
        print s.split(word)[1]
are good

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM