Python program to concatenate Strings around K

String concatenation around a delimiter involves combining strings that appear before and after a specific character K. This technique is useful for merging related string elements separated by a common delimiter.

Syntax

The general approach uses iteration to identify patterns where strings are separated by the delimiter K ?

while index < len(list):
    if list[index + 1] == K:
        combined = list[index] + K + list[index + 2]
        index += 2
    result.append(element)
    index += 1

Example

Here's how to concatenate strings around the delimiter "+" ?

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

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

K = "+"
print("The delimiter K is:", K)

my_result = []
index = 0

while index < len(my_list):
    element = my_list[index]
    
    # Check if next element is K and we have element after K
    if (index < len(my_list) - 1) and my_list[index + 1] == K:
        element = element + K + my_list[index + 2]
        index += 2  # Skip the K and next element
    
    my_result.append(element)
    index += 1

print("The result is:")
print(my_result)
The list is:
['python', '+', 'is', 'fun', '+', 'to', 'learn']
The delimiter K is: +
The result is:
['python+is', 'fun+to', 'learn']

How It Works

The algorithm processes the list sequentially:

  • Pattern Detection: When the next element equals K, it combines current + K + following element
  • Index Management: Skips 2 positions after concatenation to avoid reprocessing
  • Normal Processing: Single elements are added as-is when no K pattern is found

Alternative Approach Using Regular Expression

For more complex patterns, you can use string operations ?

def concatenate_around_k(data, delimiter):
    result = []
    i = 0
    
    while i < len(data):
        if i < len(data) - 2 and data[i + 1] == delimiter:
            # Concatenate: element + delimiter + next_element
            combined = data[i] + delimiter + data[i + 2]
            result.append(combined)
            i += 3  # Skip processed elements
        else:
            result.append(data[i])
            i += 1
    
    return result

# Example usage
words = ["hello", "-", "world", "test", "-", "case"]
output = concatenate_around_k(words, "-")
print("Input:", words)
print("Output:", output)
Input: ['hello', '-', 'world', 'test', '-', 'case']
Output: ['hello-world', 'test-case']

Conclusion

String concatenation around K combines elements separated by a delimiter into single strings. Use index management to skip processed elements and avoid duplicate concatenations.

Updated on: 2026-03-26T01:14:11+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements