I want to strip all characters after a third character, say – for instance.
I found this code online and it works but I’m having trouble learning how it works and wanted to ask so I can understand it fully.
def indexList(s, item, i=0):
"""
Return an index list of all occurrances of 'item' in string/list 's'.
Optional start search position 'i'
"""
i_list = []
while True:
try:
i = s.index(item, i)
i_list.append(i)
i += 1
except:
break
return i_list
def strip_chrs(s, subs):
for i in range(indexList(s, subs)[-1], len(s)):
if s[i+1].isalpha():
return data[:i+1]
data = '115Z2113-3-777-55789ABC7777'
print strip_chrs(data, '-')
Here’s my questions
on the while True: line what’s true?
Also on the except: Except what? and why does is a break coded there?
Thanks in advance!
Here is a way:
How it works:
sis split into a list at each occurrence of the delimiterdusings.split(d). We use the second argument tosplitto indicate the maximum number of splits to do (since there’s no reason to keep splitting after the firstntimes). The result is a list, such as["115Z2113", "3", "777", "55789ABC7777"]nitems of the list is taken using[:n]. The result is another list, such as["115Z2113", "3", "777"]dbetween each item of the list,usingd.join(...), resulting in, for example,"115Z2113-3-777"