How to split a string at every nth character in Python

Splitting a string at every nth character returns a list of strings that are of length n, but for the last split string in the list 0 < len(last_string) <= n because the entire string does not need to be of multiple of n.

Solution for How to split a string at every nth character in Python : You can use range() and slicing syntax to split a string at every nth character Use a for-loop and range(start, stop, step) to iterate over a range from start to stop where stop is the len(string) and step is every number of characters where the string will be split. Use string slicing syntax string[index : index + step] to acquire a string with step characters. Use list.append() to add that previously described string to a list.

Use list comprehension for a more compact implementation.

a_string = "abcde"


how-to-split-a-string-at-every-nth-character-in-python