Python program to Concatenate Kth index words of String


The string is the immutable data structure which stores the data in the string format. It can be created by using the str() method or by giving the data in the single or double quotes. It accesses the elements of the string we use indexing. In Indexing we have negative indexing and positive indexing where as in negative indexing we will access the last element using -1 and (–length of string) to the first element. In positive indexing we will give 0 to the first element and (length of string - 1) to the last element.

Now, in this article we are going to concatenate the Kth index words of a string by using different approaches available in python. Let’s see each approach in detail.

Using Loops

In this approach, we split the input string into a list of words using the split() method. Then, we iterate over the words and check if the index is a multiple of k. If it is, we concatenate the word with a space to the result string. Finally, we remove any leading or trailing spaces from the resulting string using the strip() method.

Example

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)

Output

This

Using list comprehension and join()

In this approach, we use list comprehension to create a new list containing only the words at indices that are multiples of k. We then use the join() method to concatenate the elements of the new list into a single string, separating them by spaces.

Example

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)

Output

This a string test program

Using slicing and join()

In this approach we use list slicing to extract the words at indices that are multiples of k. The slicing words[::k] starts from the first element and selects every kth element. We then use the join() method to concatenate the selected words into a single string, separating them by spaces.

Example

def concatenate_kth_words(string, k):
   words = string.split()  # Split the string into a list of words
   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)

Output

This a string test program

Updated on: 02-Aug-2023

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements