Python program to Concatenate Kth index words of String

Given a string with words, concatenate Kth index of each word.

Input : test_str = ‘geeksforgeeks best geeks’, K = 3 
Output : ktk 
Explanation : 3rd index of “geeksforgeeks” is k, “best” has ‘t’ as 3rd element.

Input : test_str = ‘geeksforgeeks best geeks’, K = 0 
Output : gbg 

Method #1 : Using join() + list comprehension + split()

In this, we perform the task of splitting to get all the words and then use list comprehension to get all Kth index of words, join() is used to perform concatenation.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# initializing string
test_str = 'geeksforgeeks best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 2
  
# joining Kth index of each word
res = ''.join([sub[K] for sub in test_str.split()])
      
# printing result 
print("The K joined String is : " + str(res))

chevron_right


Output:

The original string is : geeksforgeeks best for geeks
The K joined String is : esre

Method #2 : Using loop + join()

In this, we perform the task of getting the Kth index elements using a loop in a brute-force manner and then concatenating using join().

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# initializing string
test_str = 'geeksforgeeks best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 2
  
# getting Kth element of each word
temp = []
for sub in test_str.split():
  temp.append(sub[K])
  
# joining together  
res = ''.join(temp)
      
# printing result 
print("The K joined String is : " + str(res))

chevron_right


Output:

The original string is : geeksforgeeks best for geeks
The K joined String is : esre



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.