Is there a way to split a string by every nth separator in Python?

前端 未结 6 1965
时光取名叫无心
时光取名叫无心 2020-12-05 23:17

For example, if I had the following string:

\"this-is-a-string\"

Could I split it by every 2nd \"-\" rather than every \"-\" so that it returns two values (\

6条回答
  •  既然无缘
    2020-12-06 00:11

    EDIT: The original code I posted didn't work. This version does:

    I don't think you can split on every other one, but you could split on every - and join every pair.

    chunks = []
    content = "this-is-a-string"
    split_string = content.split('-')
    
    for i in range(0, len(split_string) - 1,2) :
        if i < len(split_string) - 1:
            chunks.append("-".join([split_string[i], split_string[i+1]]))
        else:
            chunks.append(split_string[i])
    

提交回复
热议问题