
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
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.
- Related Articles
- C++ Program to Concatenate Two Strings
- How to concatenate two strings in Python?
- C++ program to concatenate strings in reverse order
- Program to find smallest value of K for K-Similar Strings in Python
- Python Program to Group Strings by K length Using Suffix
- Python – Concatenate Strings in the Given Order
- Python Program to Concatenate Two Arrays
- How to concatenate strings in R?
- Concatenate strings in Arduino
- What is the most efficient way to concatenate many Python strings together?
- Program to find value of K for K-Similar Strings in C++
- How to concatenate two strings using Java?
- How to concatenate several strings in JavaScript?
- Different ways to concatenate Strings in Java
- How to concatenate two strings in C#?
