本文介绍了找到第 n 个 '|' 之后的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个字符串如下:
1|2||||auc|0|1||0|||76u| ^返回第 5 个|"之后的子字符串的最有效方法是什么?例如,给定上面的字符串,结果应该是:
what is the most efficient way to return the substring after the 5th '|'? For example, given the above string, the result should be:
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 个 |s,这可能会导致不希望的结果,例如,
Note, this will cause possibly undesired results if there's not at least 5 |s, eg,
'1|2'.split('|', 5)[-1] # returns 2 - which isn't *after* the 5th存在于字符串中,因此您可能希望将其包装在 try/except 中并强制处理没有足够 | 的情况,以便结果 在第 5 个之后 是空的,因为没有 5 个.
present in the string, so you may wish to wrap it in a try/except and force handle the case where there aren't sufficient |s so that the result after the 5th is empty as there wasn't 5 present.
try: rest = s.split('|', 5)[5] except IndexError: rest = ''更多推荐
找到第 n 个 '
发布评论