split string every 13 characters in python

To split a string every 13 characters in python, we can iterate through the string and split it up using slicing. Here's an example code snippet:

main.py
def split_string(string):
    return [string[i:i+13] for i in range(0, len(string), 13)]

string = "HelloWorldHelloWorldHelloWorldHelloWorld"
print(split_string(string))
170 chars
6 lines

This code will output the following list:

main.py
['HelloWorldHel', 'loWorldHelloW', 'orldHelloWorl', 'dHelloWorld']
67 chars
2 lines

The split_string function takes in a string argument, and then uses a list comprehension to iterate through the string, slicing it into 13-character substrings using the range function.

We use range(0, len(string), 13) to generate a series of indices where we can slice the string. The step parameter is set to 13, so we slice the string 13 characters at a time.

We slice the string using string[i:i+13] where i is the index of the current slice, and i+13 is the index of the end of the slice.

Finally, the function returns a list of the sliced substrings.

gistlibby LogSnag