0

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

2
  • 1
    What have you tried so far? Also, you probably don't want to call a Python variable 'string' Commented Mar 27, 2022 at 11:30
  • Tried to solve it with for loop n = 6 string = "Cipher Programming - 101!" str_size = len(string) part_size = n k = 0 for i in string: if k % part_size == 0: print() print(i, end="") k += 1 but I am trying to write the code inside function returning only list (without using print) Commented Mar 27, 2022 at 11:39

2 Answers 2

1

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)]
Sign up to request clarification or add additional context in comments.

4 Comments

It's actually a list comprehension, not a normal for loop.
@Bialomazur Yes, my bad
@AntónioRebelo what does the third line do? when I run it says line needs declaration. If you shortened your code, could you please upload the full version of it?
Check @Bialomazur 's solution for a more straightforward solution that is easier to understand. If you have not come across list-comprehensions I suggest you do so, this is what I used in that solution and if you haven't heard of them it can be quite tricky to understand how it works. I am not sure what "needs declaration" means but I think the code should work.
1

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

2 Comments

Please see António Rebelo's answer for an elegant solution
@ArthurKing I have, please read my statement before the actual code. It was my intention to make the code longer with more 'baby-steps' involved. I think it plays together quite well with António Rebelo's much shorter solution with a list-comprehension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.