Python program to concatenate Strings around K

When it is required to concatenate strings around ‘K’, a simple iteration and the ‘append’ method is used.


Below is a demonstration of the same −

my_list = ["python", "+", 'is', 'fun', "+", 'to', 'learn']

print("The list is :")

K = "+"
print("The value of K is :")

my_result = []
index = 0

while index < len(my_list):

   element = my_list[index]

   if (index < len(my_list) - 1) and my_list[index + 1] == K:
      element = element + K + my_list[index + 2]

      index += 2
   index += 1

print("The result is :")


The list is :
['python', '+', 'is', 'fun', '+', 'to', 'learn']
The value of K is :
The result is :
['python+is', 'fun+to', 'learn']


  • A list of strings is defined and is displayed on the console.

  • The value of ‘K’ is assigned a string and displayed on the console.

  • An empty list is defined.

  • An integer value is initialized to 0.

  • The integer value is checked to be less than the length of the list.

  • If so, the element at the specific index is assigned to a variable.

  • The integer variable and length of the list are compared again, and the element is assigned a different value.

  • The integer is incremented by 2.

  • In the end, this variable is appended to the empty list, and the integer is incremented by 1.

  • The result is the variable which is displayed on the console.