Split string at nth occurrence of a given character

后端 未结 7 1959
攒了一身酷
攒了一身酷 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:13

    >>>import re
    >>>str= '20_231_myString_234'
    
    >>> occerence = [m.start() for m in re.finditer('_',str)]  # this will give you a list of '_' position
    >>>occerence
    [2, 6, 15]
    >>>result = [str[:occerence[1]],str[occerence[1]+1:]] # [str[:6],str[7:]]
    >>>result
    ['20_231', 'myString_234']
    

提交回复
热议问题