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?
If you need to remove everything before last occurrence of a character, use the str. rfind() method.
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.
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.
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'
You can use str.join()
and str.partition()
:
''.join('have an egg please'.partition('egg')[1:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With