在给定字符的第 n 次出现处拆分字符串 [英] Split string at nth occurrence of a given character

查看:55
本文介绍了在给定字符的第 n 次出现处拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定定界符出现第 n 次后,是否有一种 Python 方式来分割字符串?

Is there a Python-way to split a string after the nth occurrence of a given delimiter?

给定一个字符串:

'20_231_myString_234'

它应该被拆分为(在第二次出现后,分隔符为_"):

It should be split into (with the delimiter being '_', after its second occurrence):

['20_231', 'myString_234']

或者是唯一的方法来完成计数、拆分和加入?

Or is the only way to accomplish this to count, split and join?

推荐答案

>>> n = 2
>>> groups = text.split('_')
>>> '_'.join(groups[:n]), '_'.join(groups[n:])
('20_231', 'myString_234')

似乎这是最易读的方式,替代的是正则表达式)

Seems like this is the most readable way, the alternative is regex)

这篇关于在给定字符的第 n 次出现处拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆