查找第 n 个 '|' 之后的子串

Find the sub-string after nth '|'

给定一个字符串如下:

1|2||||auc|0|1||0|||76u|
      ^ 

return 第 5 个“|”之后的子字符串的最有效方法是什么? 例如,给定上面的字符串,结果应该是:

auc|0|1||0|||76u|
def get_substring(my_string):
    count = 0
    for i, char in enumerate(my_string):
        if char == '|':
            count += 1
            if count == 5:
                return my_string[i+1:]

使用str.split:

s = '1|2||||auc|0|1||0|||76u|'
print s.split('|', 5)[-1]
# auc|0|1||0|||76u|

请注意,如果没有至少 5 | 秒,这可能会导致意外结果,例如,

'1|2'.split('|', 5)[-1]
# returns 2 - which isn't *after* the 5th

出现在字符串中,因此您可能希望将其包装在 try/except 中并强制处理 | 不足的情况,以便结果 第 5 个之后 是空的,因为没有 5 个出现。

try:
    rest = s.split('|', 5)[5]
except IndexError:
    rest = ''

使用带限制的str.split() method(第二个参数):

input_string.split('|', 5)[-1]

这会将字符串拆分 5 次,并取最后一个元素,其中剩余的 | 个字符未拆分。

如果字符串中 少于 | 个字符,您仍然会从拆分中获取最后一个元素,因为 [-1] 从结束。这意味着即使拆分中有 个管道符号,表达式也会继续工作。

演示:

>>> input_string = '1|2||||auc|0|1||0|||76u|'
>>> input_string.split('|', 5)
['1', '2', '', '', '', 'auc|0|1||0|||76u|']
>>> input_string.split('|', 5)[-1]
'auc|0|1||0|||76u|'

并引用文档:

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

s = '1|2||||auc|0|1||0|||76u|'
sre =  re.compile('([^|]*)(' + r*4 + ')(.*)')

sre.search(s).groups()
Out[39]: ('1', '|2|||', '|auc|0|1||0|||76u|')

sre.search(s).group(3)[1:]
Out[40]: 'auc|0|1||0|||76u|'