- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Insert character in each duplicate string after every K elements
When it is required to insert character in each duplicate string after every ‘K’ elements, a method is defined that uses ‘append’ method, concatenation operator and list slicing.
Below is a demonstration of the same −
def insert_char_after_key_elem(my_string, my_key, my_char): my_result =  for index in range(0, len(my_string), my_key): my_result.append(my_string[:index] + my_char + my_string[index:]) return str(my_result) my_string = 'PythonToCode' print("The string is :") print(my_string) K = 2 print("The value of K is ") print(K) add_char = ";" print("The result is :") print(insert_char_after_key_elem(my_string, K, add_char))
The string is : PythonToCode The value of K is 2 The result is : [';PythonToCode', 'Py;thonToCode', 'Pyth;onToCode', 'Python;ToCode', 'PythonTo;Code', 'PythonToCo;de']
A method named ‘insert_char_after_key_elem’ is defined that takes a string, a key and a character as parameters.
An empty list is defined.
The string and the key passed as parameters is iterated over.
List slicing and concatenation operator ‘+’ are used to append the output to the empty list.
This is converted to a string and displayed as output of the method
Outside the method, a string is defined, and is displayed on the console.
The ‘key’ value and the ‘character’ value are defined.
The method is called by passing the required parameters.
The output is displayed on the console.
- Python – Sort String list by K character frequency
- Program to find string after deleting k consecutive duplicate characters in python
- Python – K middle elements
- Find k-th character of decrypted string - Set – 2 in Python
- Python – Reform K digit elements
- Python – Remove Columns of Duplicate Elements
- How to insert content after each of the matched elements using jQuery?
- Frequency of each character in String in Python
- Python program to Mark duplicate elements in string
- Python – Next N elements from K value
- Python – Random insertion of elements K times
- Python – Character indices Mapping in String List
- Python – Rows with K string in Matrix
- Find k-th character of decrypted string - Set – 2 in C++