Python | Split string in groups of n consecutive characters
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', 'oor', 'gee', 'ks'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567]
Method #1: Using list comprehension
# Python code to split string # by every 3th number # String initialization string = "Geeksforgeeks" # Defining splitting point n = 3 # Using list comprehension out = [(string[i:i+n]) for i in range(0, len(string), n)] # Printing output print(out) |
chevron_right
filter_none
Output:
['Gee', 'ksf', 'org', 'eek', 's']
Method #2: Using zip_longest
# Python code to split string of number # and character into every 4th number # Importing from itertools import zip_longest # Group function using zip_longest to split def group(n, iterable, fillvalue=None): args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) # String initialization str = '123GeeksForGeeks4567' # Split point n=4 # list of seperated string out_string = [''.join(lis) for lis in group(n, str, '')] # Output list initialization out_no = [] # Converting list of string into list of integer for a in out_string: out_no.append(a) # Printing list print(out_no) |
chevron_right
filter_none
Output:
['123G', 'eeks', 'ForG', 'eeks', '4567']
Recommended Posts:
- Python | Split string into list of characters
- Python | Split tuple into groups of n
- Python String | split()
- How to split a string in C/C++, Python and Java?
- Python program to split and join a string
- Python | String Split including spaces
- Split a string in equal parts (grouper in Python)
- Python | Split CamelCase string to individual strings
- Python | Pandas Split strings into two List/Columns using str.split()
- Python | Extract only characters from given string
- Iterate over characters of a string in Python
- Python | Splitting string to list of characters
- Concatenated string with uncommon characters in Python
- Python | Check if frequencies of all characters of a string are different
- Check if both halves of the string have same set of characters in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



