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

前端 未结 6 1977
时光取名叫无心
时光取名叫无心 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:05

    Here’s another solution:

    span = 2
    words = "this-is-a-string".split("-")
    print ["-".join(words[i:i+span]) for i in range(0, len(words), span)]
    

提交回复
热议问题