How can I remove everything in a string until a character(s) are seen in Python -
say have string , want remove rest of string before or after characters seen
for example, strings have 'egg' in them:
"have egg please" "my eggs good"
i want get:
"egg please" "eggs good"
and same question how can delete string in front of characters?
you can use str.find
method simple indexing :
>>> s="have egg please" >>> s[s.find('egg'):] 'egg please'
note str.find
returns -1
if doesn't find sub string , returns last character of string.so if not sure string contain sub string better check 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!
Comments
Post a Comment