Python | Insert value after each k letters in given list of string
Given a list of string, write a Python program to Insert some letter after each k letters in given list of strings.
As we know inserting element in a list is quite common, but sometimes we need to operate on list of strings by considering each letter and insert some repeated elements some fixed frequency. Let’s see how to achieve this task using Python.
Method #1: Using enumerate() method
# Python program to insert value after # each k letters in given list of string list1 = ['p', 'y', 't', 'h', 'o', 'n'] # printing original list print ("Original list : " + str(list1)) # initializing k k = 'G' # initializing N N = 2 # using join() + enumerate() # inserting K after every Nth number output = list(''.join(i + k * (N % 2 == 1) for N, i in enumerate(list1))) # printing result print ("The lists after insertion : " + str(output)) |
Original list : ['p', 'y', 't', 'h', 'o', 'n'] The lists after insertion : ['p', 'y', 'G', 't', 'h', 'G', 'o', 'n', 'G']
Method #2: Using itertools
# Python program to insert value after # each k letters in given list of string from itertools import chain list1 = ['p', 'y', 't', 'h', 'o', 'n'] # printing original list print ("Original list : " + str(list1)) # initializing k k = 'x' # initializing N N = 3 # inserting K after every Nth number output = list(chain(*[list1[i : i + N] + [k] if len(list1[i : i + N]) == N else list1[i : i + N] for i in range(0, len(list1), N)])) # printing result print ("The lists after insertion : " + str(output)) |
Original list : ['p', 'y', 't', 'h', 'o', 'n'] The lists after insertion : ['p', 'y', 't', 'x', 'h', 'o', 'n', 'x']
Recommended Posts:
- Python | Insert the string at the beginning of all items in a list
- Python | First N letters string construction
- Python | Ways to sort letters of string alphabetically
- Python list | insert()
- Python | Insert after every Nth element in a list
- Python | Insert list in another list
- Python | Split given list and insert in excel file
- Python program to insert an element into sorted list
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Python | Insert a number in string
- Python | Convert list of string to list of list
- Python | Convert list of numerical string to list of Integers
- Python | Convert list of string into sorted list of integer
- Python | Convert a string representation of list into list
- Python | Convert string enclosed list to list
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.



