Ways to slice a string?

后端 未结 6 634
渐次进展
渐次进展 2020-12-01 21:16

I have a string, example:

s = \"this is a string, a\"

Where a \',\' (comma) will always be the 3rd to the last character, aka

6条回答
  •  醉梦人生
    2020-12-01 22:17

    To slice a string of arbitrary length into multiple equal length slices of arbitrary length you could do

    def slicer(string, slice_length):
        return [string[i:i + slice_length]
                for i in xrange(0, len(string), slice_length)]
    

    If slice_length does not divide exactly into len(string) then there will be a single slice at the end of the list that holds the remainder.

提交回复
热议问题