Skip to content
Related Articles

Related Articles

Python program to Concatenate Kth index words of String

View Discussion
Improve Article
Save Article
  • Last Updated : 26 Aug, 2022
View Discussion
Improve Article
Save Article

Given a string with words, concatenate the 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




# 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))


Output

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

Time Complexity: O(n)
Auxiliary Space: O(n)

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




# 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))


Output

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

Time Complexity: O(n)
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!