给定一个字符串如下:
1|2||||auc|0|1||0|||76u|
^
返回第 5 个“|”之后的子字符串的最有效方法是什么? 例如,给定上面的字符串,结果应该是:
auc|0|1||0|||76u|
请您参考如下方法:
使用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 = ''
