kim
kim

Reputation: 17

split strings in a list by characters

I want to make 'example' into a list that is separated by a certain pattern. like this:

example = 'abcdefghijklmnopqrstuvwx'

mylist1 = ['abc', 'def', 'ghi','jkl', 'mno', 'pqr','stu','vwx']

mylist2 = ['a','bcd','ef', 'g','hij','kl','m','nop','qr','s','tuv','wx']

mylist3 = ['ab','cde','f','gh','ijk','l','mn','opq','r','st','uvw','x']

The pattern for mylist2, it is 1-3-2, and for mylist3, it is 2-3-1

I was able to make mylist1 by using the following code:

mylist1 = []
for i in range(0, len(example), 3):
    mylist1.append(example[i:i+3])

but I am having trouble with making mylist2 and mylist3.

Upvotes: 0

Views: 54

Answers (1)

ex4
ex4

Reputation: 2428

How about this generic approach. There is more pythonic way to do it, someone could probably do the same as a oneliner. But with this code you probably can understand what is going on.

def slicer(data, pattern):
    """
    @param data: The string you want to split
    @param pattern: tuple showing pattern you want to use
    @returns: sliced list
    """
    i = 0
    res = []
    while i < len(data): #Continue processing the text until we reach the end
       for slice in pattern:  #Loop through your pattern here
           if data[i:i+slice]:
               #if there is anything to add, we add it to result.         
               res.append(data[i:i+slice])
           i += slice
    return res

Example of usage

>>> slicer ("abcdefghijklmnopqrstuvwxyz",(1,2,3))
['a', 'bc', 'def', 'g', 'hi', 'jkl', 'm', 'no', 'pqr', 's', 'tu', 'vwx', 'y', 'z']

>>> slicer ("abcdefghijklmnopqrstuvwxyz",(1,3,1))
['a', 'bcd', 'e', 'f', 'ghi', 'j', 'k', 'lmn', 'o', 'p', 'qrs', 't', 'u', 'vwx', 'y', 'z']

Upvotes: 2

Related Questions