String line after python character third appearance

I want to delete all characters after the third character, for example, for example.

I found this code online and it works, but I have problems learning how it works and wanted to ask so that I can fully understand it.

 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 are my questions while True: string, what is the truth? Also except: except for what? and why is the gap encoded here?

Thanks in advance!

+5
source share
4 answers

Here is a way:

def trunc_at(s, d, n=3):
    "Returns s truncated at the n'th (3rd by default) occurrence of the delimiter, d."
    return d.join(s.split(d, n)[:n])

print trunc_at("115Z2113-3-777-55789ABC7777", "-")

How it works:

  • s d s.split(d). split, ( n ). , ["115Z2113", "3", "777", "55789ABC7777"]
  • [:n] n . , ["115Z2113", "3", "777"]
  • , d , d.join(...), , , "115Z2113-3-777"
+22

:

data = '115Z2113-3-777-55789ABC7777'
strip_character = "-"
>>> strip_character.join(data.split(strip_character)[:3])
'115Z2113-3-777'
+7

 while True:

. , break. except , , break .

+4
source

In "while True," True is simply a constant value of True. Thus, although True is a loop - forever or until it is broken.

the exception uses the exception that occurs when s.index does not find more lines after i as a way to break the loop. This is a bad thing.

try something like this (pseudocode):

while you still have string left:
   get index of next '-'
   if found, add 1 to count
   if count == 3:
      return s[index+1:]

s[index+1:] returns the substring from the character following the index to the end.

+1
source

All Articles