Split string at nth occurrence of a given character

后端 未结 7 1951
攒了一身酷
攒了一身酷 2020-11-30 05:50

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

Given a string:

\'20_231_myString_234\'

It s

7条回答
  •  春和景丽
    2020-11-30 06:11

    >>> 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)

提交回复
热议问题