Skip to content
Related Articles

Related Articles

Python – Selective consecutive Suffix Join

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Jul, 2022
View Discussion
Improve Article
Save Article

Given a list of elements, the task is to write a Python program to perform a join of consecutive strings according to the suffix of each string.

Input : test_list = [“Geeks-“, “for-“, “Geeks”, “is”, “best-“, “for”, “geeks”, suff = ‘-‘ 
Output : [‘Geeks-for-Geeks’, ‘is’, ‘best-for’, ‘geeks’] 
Explanation : Strings are joined to next which have “-” as suffix.

Input : test_list = [“Geeks*”, “for*”, “Geeks”, “is”, “best*”, “for”, “geeks”, suff = ‘*’ 
Output : [‘Geeks*for*Geeks’, ‘is’, ‘best*for’, ‘geeks’] 
Explanation : Strings are joined to next which have “*” as suffix. 

Approach : Using loop + endswith() + join()

In this we perform the task of joining using join() and endswith() performs the task of conditional checks for suffix as defined. 

Python3




# Python3 code to demonstrate working of
# Selective consecutive Suffix Join
# Using loop + endswith() + join()
 
# initializing list
test_list = ["Geeks-", "for-", "Geeks", "is",
             "best-", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing suffix
suff = '-'
 
res = []
temp = []
for ele in test_list:
    temp.append(ele)
 
    # conditionally test values
    if not ele.endswith(suff):
        res.append(''.join(temp))
        temp = []
if temp:
    res.append(''.join(temp))
 
# printing result
print("The joined result : " + str(res))

Output:

The original list is : [‘Geeks-‘, ‘for-‘, ‘Geeks’, ‘is’, ‘best-‘, ‘for’, ‘geeks’] The joined result : [‘Geeks-for-Geeks’, ‘is’, ‘best-for’, ‘geeks’]

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!