1 def get_string(string, key): 2 chars = ['。', ',', '.', ',', '\\n'] 3 print("old str:" + string) 4 match = re.search(key, string) 5 if match: 6 start = match.start() 7 end = match.end() 8 beforeText = string[0:start] 9 endText = string[end: len(string)] 10 print("beforeText:" + beforeText) 11 print("endText:" + endText) 12 13 beforeIndex = getBeforeCharIndex(beforeText, chars) 14 if beforeIndex > -1: 15 beforeText = beforeText[0:beforeIndex] 16 17 nextIndex = getNextCharIndex(endText, chars) 18 if nextIndex < len(endText): 19 endText = endText[nextIndex:len(endText)] 20 21 print("result str:" + beforeText + endText) 22 23 24 def getBeforeCharIndex(str, chars): 25 index = -1 26 for c in chars: 27 cIndex = str.rfind(c) 28 if (cIndex > index): 29 index = cIndex 30 return index 31 32 33 def getNextCharIndex(str, chars): 34 index = len(str) 35 for c in chars: 36 try: 37 cIndex = str.index(c) 38 if (cIndex < index): 39 index = cIndex 40 except Exception as e: 41 print(c) 42 # print(e) 43 return index
标签:index,string,Python,chars,endText,beforeText,str,字符串,哈哈哈 From: https://www.cnblogs.com/bluejump/p/17561329.html