找到第 n 个 '

编程入门 行业动态 更新时间:2024-10-28 10:25:18
本文介绍了找到第 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 个 '

本文发布于:2023-11-29 19:10:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:到第

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!