Home > Net >  split string by certain number and save the result as a list in python
split string by certain number and save the result as a list in python

Time:03-28

So I have a string (string = "Cipher Programming - 101!"), I want to split it by six chars (spaces and special symbols included) and store result as list in Python.

expected output: ['Cipher', ' Progr', 'amming', ' - 101', '!']

CodePudding user response:

Just a normal for loop will do the trick:

string = "Cipher Programming - 101!"
n = 6
[line[i:i n] for i in range(0, len(string), n)]

CodePudding user response:

The answer above works very well - is very compact and elegant, but for sake of understanding it a bit better, I've decided to include an answer with a regular for-loop.

string = "Cipher Programming - 101!"  # can be any string (almost)

result = []
buff = ""
split_by = 6  # word length for each string inside of 'result'

for index, letter in enumerate(string):
    buff  = letter

    # first append and then reset the buffer
    if (index   1) % split_by == 0:
        result.append(buff)
        buff = ""

    # append the buffer containing the remaining letters
    elif len(string) - (index   1) == 0:
        result.append(buff)

print(result) # output: ['Cipher', ' Progr', 'amming', ' - 101', '!']
  • Related