简体   繁体   English

第三次出现字符python后去掉字符串

[英]Strip string after third occurrence of character python

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? 这是我关于while的问题:行什么是真的? Also on the except: Except what? 另外除了:除了什么? and why does is a break coded there? 为什么在那里编码?

Thanks in advance! 提前致谢!

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: 这个怎么运作:

  1. The string s is split into a list at each occurrence of the delimiter d using s.split(d) . 使用s.split(d)在每次出现分隔符d将字符串s拆分为列表。 We use the second argument to split to indicate the maximum number of splits to do (since there's no reason to keep splitting after the first n times). 我们使用第二个参数进行split以指示要执行的最大拆分数(因为在前n次之后没有理由继续拆分)。 The result is a list, such as ["115Z2113", "3", "777", "55789ABC7777"] 结果是一个列表,例如["115Z2113", "3", "777", "55789ABC7777"]
  2. A slice of the first n items of the list is taken using [:n] . 使用[:n]获取列表的前n项的切片。 The result is another list, such as ["115Z2113", "3", "777"] 结果是另一个列表,例如["115Z2113", "3", "777"]
  3. The list is joined back into a string, placing the delimiter d between each item of the list,using d.join(...) , resulting in, for example, "115Z2113-3-777" 该列表连接回一个字符串,使用d.join(...)将分隔符d放在列表的每个项目之间,从而产生例如"115Z2113-3-777"

In a one-liner way : 以单行方式:

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

The line 这条线

 while True:

creates an infinite loop. 创造一个无限循环。 It's just going to keep looping there until either the program crashes or a break is called. 它只是继续循环,直到程序崩溃或break为止。 The except line is an exception handler that is going to catch any exceptions, at which point break is called exiting the infinite loop. except行是一个异常处理程序,它将捕获任何异常,此时break被称为退出无限循环。

On the "while True", True is simply the constant value True. 在“while True”中,True只是常量值True。 So while True is loop-forever or until broken. 因此,虽然True是永久循环或直到破碎。

the except is using the exception that happens when s.index finds no more string after i as a way to break the loop. 除了使用s.index在i之后找不到更多字符串作为打破循环的方法时发生的异常。 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:]

the s[index+1:] returns the substring from the character following index, to the end. s[index+1:]返回索引后面字符的子字符串到结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM