Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character.
Examples:
Input : str = "Geeksforgeeks", n = 3
Output : ['Gee', 'ksf', 'org', 'eek', 's']
Input : str = "1234567891234567", n = 4
Output : [1234, 5678, 9123, 4567]
Method #1: Using list comprehension
Python3
string = "Geeksforgeeks"
n = 3
out = [(string[i:i+n]) for i in range(0, len(string), n)]
print(out)
Method #2: Using zip_longest
Python3
from itertools import zip_longest
def group(n, iterable, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
str = '123GeeksForGeeks4567'
n=4
out_string = [''.join(lis) for lis in group(n, str, '')]
out_no = []
for a in out_string:
out_no.append(a)
print(out_no)
Output ['123G', 'eeks', 'ForG', 'eeks', '4567']
Method 3: Using a for loop and string slicing.
Initialize an empty list to store the substrings. Define the splitting point, i.e., n=3. Create a for loop to iterate over the string. In each iteration, append the substring to the list using string slicing. Print the output list.
Python3
string = "Geeksforgeeks"
n = 3
out = []
for i in range(0, len(string), n):
out.append(string[i:i+n])
print(out)
Output ['Gee', 'ksf', 'org', 'eek', 's']
Time complexity: O(n), where n is the length of the input string. Auxiliary space: O(n), as we are storing each substring in a list.
Last Updated :
23 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...