查找第 n 个“|”之后的子字符串

q09*_*987 1 python split python-2.7

给定一个字符串如下:

1|2||||auc|0|1||0|||76u|
      ^ 
Run Code Online (Sandbox Code Playgroud)

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

auc|0|1||0|||76u|
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 5

使用str.split

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

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

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

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

try:
    rest = s.split('|', 5)[5]
except IndexError:
    rest = ''
Run Code Online (Sandbox Code Playgroud)