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

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

    I think several of the already given solutions are good enough, but just for fun, I did this version:

    def twosplit(s,sep):
      first=s.find(sep)
      if first>=0:
        second=s.find(sep,first+1)
          if second>=0:
            return [s[0:second]] + twosplit(s[second+1:],sep)
          else:
            return [s]
        else:
          return [s]
      print twosplit("this-is-a-string","-")
    

提交回复
热议问题