saba morchilashvili
saba morchilashvili

Reputation: 15

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

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', '!']

Upvotes: 0

Views: 76

Answers (2)

Bialomazur
Bialomazur

Reputation: 1141

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', '!']

Upvotes: 1

António Rebelo
António Rebelo

Reputation: 304

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)]

Upvotes: 1

Related Questions