Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to Concatenate Kth index words of String
Python strings are immutable data structures that store text data. We can access string elements using indexing, where positive indexing starts from 0 and negative indexing starts from -1. When working with strings containing multiple words, we often need to extract specific words based on their positions.
In this article, we'll explore different approaches to concatenate words at every Kth index position from a string using Python.
Using Loops
This approach splits the string into words and iterates through them, selecting words at indices that are multiples of K ?
def concatenate_kth_words(string, k):
words = string.split()
result = ""
for i in range(len(words)):
if i % k == 0:
result += words[i] + " "
return result.strip()
my_string = "This is a sample string to test the program"
k = 2
concatenated_words = concatenate_kth_words(my_string, k)
print(concatenated_words)
This a string test program
Using List Comprehension and join()
List comprehension provides a more concise way to filter words at Kth indices and join them into a single string ?
def concatenate_kth_words(string, k):
words = string.split()
result = " ".join([words[i] for i in range(len(words)) if i % k == 0])
return result
my_string = "This is a sample string to test the program"
k = 2
concatenated_words = concatenate_kth_words(my_string, k)
print(concatenated_words)
This a string test program
Using Slicing and join()
List slicing with step parameter offers the most elegant solution by directly extracting every Kth element ?
def concatenate_kth_words(string, k):
words = string.split()
result = " ".join(words[::k])
return result
my_string = "This is a sample string to test the program"
k = 2
concatenated_words = concatenate_kth_words(my_string, k)
print(concatenated_words)
This a string test program
Comparison of Methods
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| Loops | Good | Slower | Longer |
| List Comprehension | Good | Fast | Medium |
| Slicing | Excellent | Fastest | Shortest |
Conclusion
The slicing method words[::k] is the most efficient and readable approach for concatenating Kth index words. List comprehension offers good balance between readability and performance, while loops provide explicit control over the iteration process.
