Home > Net >  Covert a string into list & sublist with characters sepration in python
Covert a string into list & sublist with characters sepration in python

Time:10-30

Covert a string "Welcome to Baramati" into list & sublist (ex: 1st list has 3 letters ['W','E','L']. The 2nd list has 4 letters ['C','O','M','E'] and the 3rd list has 5 letters & the 6th list has 6 letters.

CodePudding user response:

You could use a generator function and some itertools:

from itertools import count, islice

def chunks(s, start=3):
    i = iter(s.replace(" ", ""))
    for c in count(start):
        if not (chunk := [*islice(i, c)]):
            return  
        yield chunk


[*chunks('Welcome to Baramati')]
# [['W', 'e', 'l'], ['c', 'o', 'm', 'e'], ['t', 'o', 'B', 'a', 'r'], ['a', 'm', 'a', 't', 'i']]

CodePudding user response:

You can do this with replace(' ', '') then only use while and get slice what you want like below:

st = 'Welcome to Baramati'
st = st.replace(' ', '')

i = 0
j = 3
res = []
while i<len(st):
    res.append([s for s in st[i:i j]])
    i = i j
    j  = 1

print(res)

Output:

[['W', 'e', 'l'],
 ['c', 'o', 'm', 'e'],
 ['t', 'o', 'B', 'a', 'r'],
 ['a', 'm', 'a', 't', 'i']]

CodePudding user response:

Here is one implementation using itertools.count:

import itertools

s = "Welcome to Baramati"
lst = [c for c in s if c != ' '] # list-ify

cnt = itertools.count(start=3)
output = []
while lst:
    output.append(lst[:(length := next(cnt))])
    lst = lst[length:]

print(output) # [['W', 'e', 'l'], ['c', 'o', 'm', 'e'], ['t', 'o', 'B', 'a', 'r'], ['a', 'm', 'a', 't', 'i']]

Apparently this also uses walrus operator := , which is available in python 3.8 .

Also, this might be slightly less memory-efficient, because it makes a temporary list. But tbh I personally like to use while something: pattern. :)

  • Related