[英]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:例如,我所有的字符串中都有 'egg':
"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 :您可以使用带有简单索引的
str.find
方法:
>>> 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.请注意,如果
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!
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.