Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 975
booberz Avatar asked Oct 15 '15 06:10

booberz


People also ask

How do you delete everything before a character in a string Python?

If you need to remove everything before last occurrence of a character, use the str. rfind() method.

How do you remove everything before a certain character in a string?

To remove everything before the first occurrence of the character '-' in a string, pass the character '-' as a separator in the partition() function. Then assign the part after the separator to the original string variable. It will give an effect that we have deleted everything before the character '-' in a string.

How do you delete something before a space in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


3 Answers

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!
like image 86
Mazdak Avatar answered Oct 23 '22 08:10

Mazdak


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'
like image 9
Fatemeh Asgarinejad Avatar answered Oct 23 '22 08:10

Fatemeh Asgarinejad


You can use str.join() and str.partition():

''.join('have an egg please'.partition('egg')[1:])
like image 3
TigerhawkT3 Avatar answered Oct 23 '22 06:10

TigerhawkT3