[英]How can I remove everything in a string until a character(s) are seen in Python
假設我有一個字符串,我想在看到某些字符之前或之后刪除字符串的其余部分
例如,我所有的字符串中都有 'egg':
"have an egg please"
"my eggs are good"
我想得到:
"egg please"
"eggs are good"
還有同樣的問題,但如何刪除除字符前面的字符串之外的所有內容?
您可以使用帶有簡單索引的str.find
方法:
>>> s="have an egg please"
>>> s[s.find('egg'):]
'egg please'
請注意,如果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
因此,輸出將是
'Stack '
和
string[index:]
會給
'Overflow'
使用正則表達式來獲取子字符串。
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.