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.

Example

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))

Output

The string is :
PythonToCode
The value of K is
2
The result is :
[';PythonToCode', 'Py;thonToCode', 'Pyth;onToCode', 'Python;ToCode', 'PythonTo;Code',
'PythonToCo;de']

Explanation

  • 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.

Updated on: 08-Sep-2021

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements