# Python program to concatenate Strings around K

PythonServer Side ProgrammingProgramming

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

## Example

Below is a demonstration of the same −

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

print("The list is :")
print(my_list)

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

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
my_result.append(element)
index += 1

print("The result is :")
print(my_result)

## Output

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

## Explanation

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

Published on 08-Sep-2021 07:16:04
Advertisements