Open In App

Python – Avoid Last occurrence of delimiter

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an Integer list, perform join with the delimiter, avoiding the extra delimiter at the end.

Input : test_list = [4, 7, 8, 3, 2, 1, 9], delim = “*” 
Output : 4*7*8*3*2*1*9 
Explanation : The rear “*” which usually occurs in concatenation, is avoided.

Input : test_list = [4, 7, 8, 3], delim = “*” 
Output : 4*7*8*3 
Explanation : The rear “*” which usually occurs in concatenation, is avoided. 

Method #1: Using String slicing

Use string slice to slice off the last character from the string after forming.  

Step by step approach :

  • A delimiter called “delim” is initialized with the value “$”.
  • A string called “res” is initialized to an empty string.
  • A for loop is used to iterate through each element in the “test_list” and append the string representation of the element with the delimiter “$” to the “res” string. This creates a joined string with the delimiter “$” separating each element in the list. However, this approach will leave a stray “$” at the end of the joined string.
  • The last occurrence of the delimiter “$” is removed from the “res” string using slicing. This is done by assigning the string “res” to a slice that excludes the last character of the string, which is the stray “$”.
  • Finally, the joined string without the last occurrence of the delimiter “$” is printed using the print() function and concatenation with the str() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using map() + join() + str()
 
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "$"
 
# appending delim to join
# will leave stray "$" at end
res = ''
for ele in test_list:
    res += str(ele) + "$"
 
# removing last using slicing
res = res[:len(res) - 1]
 
# printing result
print("The joined string : " + str(res))


Output

The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list. 

Method #2 : Using map() + join() + str()

In this, we completely avoid loop method to solve this problem, and employ map() to convert to string and join() to perform task of join.

Python3




# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using map() + join() + str()
 
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "$"
 
# map extends string conversion logic
res = delim.join(map(str, test_list))
 
# printing result
print("The joined string : " + str(res))


Output

The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9

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

Method #3: Using str.join() with list comprehension

We can use a list comprehension to convert each element of the list to a string and then use the str.join() method to join the elements with the delimiter. Finally, we can remove the last occurrence of the delimiter using string slicing.

Python3




# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "$"
 
# joining elements using list comprehension and str.join()
res = delim.join([str(ele) for ele in test_list])
 
# removing last delimiter using string slicing
res = res[:-1]
 
# printing result
print("The joined string : " + str(res))


Output

The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$

Time complexity: The time complexity of the given program is O(n), where n is the length of the input list. 
Auxiliary space: The auxiliary space used by the program is O(n), where n is the length of the input list.

Method #4: Using reduce() and lambda function:

Step-by-Step Approach:

  1. The input list is initialized as test_list.
  2. The original list is printed using the print() function.
  3. The delimiter is initialized as $
  4. The reduce() function from functools module is used to apply the lambda function to the list of integers, where the lambda function concatenates each element of the list with the delimiter in between.
  5. The resulting string is assigned to the variable res.
  6. The final result is printed using the print() function.

Python3




from functools import reduce
test_list = [4, 7, 8, 3, 2, 1, 9]
print("The Original List is : " + str(test_list))
delimiter = "$"
res = reduce(lambda x, y: str(x) + delimiter + str(y), test_list)
print("The joined string : "+res)


Output

The Original List is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9

Time Complexity:  O(n), where n is the length of the input list

This is because in this case, the lambda function is applied to the entire list in a sequential manner.

Space Complexity: O(n), where n is the length of the input list

This is because the reduce() function requires additional memory to store intermediate results.

Method #5: Using str.rstrip() 

This program is designed to remove the last occurrence of a delimiter from a list of integers and join them using the delimiter.

  • Initialize the list.
  • Print the original list.
  • Initialize the delimiter.
  • Join the list elements using the delimiter.
  • The map() function is used to convert each element of the list to a string, and then join() is used to concatenate the elements with the delimiter.
  • Remove the last occurrence of the delimiter using rstrip() method.
  • The rstrip() method is used to remove the last occurrence of the delimiter from the end of the string.
  • Print the result.

Python3




# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using str.rstrip()
 
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "$"
 
# join the list elements using the delimiter
res = delim.join(map(str, test_list))
 
# remove the last occurrence of delimiter using rstrip()
res = res.rstrip(delim)
 
# printing result
print("The joined string : " + str(res))


Output

The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list, for storing the joined string.

Method 5: Using a loop and string concatenation

Step-by-step approach:

  1. Initialize the list test_list.
  2. Initialize the delimiter delim.
  3. Initialize an empty string res.
  4. Iterate over the elements of test_list except the last one, and concatenate each element with the delimiter and add it to res.
  5. Append the last element of test_list to res.
  6. Print the resulting string.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using a loop and string concatenation
 
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "$"
 
# loop over the list and concatenate the elements with delimiter
res = ""
for i in range(len(test_list) - 1):
    res += str(test_list[i]) + delim
 
# append the last element to res
res += str(test_list[-1])
 
# printing result
print("The joined string : " + str(res))


Output

The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9

Time complexity: O(n)
Auxiliary space: O(n)



Similar Reads

Python | Split on last occurrence of delimiter
The splitting of strings has always been discussed in various applications and use cases. One of the interesting variations of list splitting can be splitting the list on delimiter but this time only on the last occurrence of it. Let's discuss certain ways in which this can be done. Method #1: Using rsplit(str, 1) The normal string split can perfor
7 min read
Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python | Ways to split strings using newline delimiter
Given a string, write a Python program to split strings on the basis of newline delimiter. Given below are a few methods to solve the given task. Method #1: Using splitlines() Step-by-step approach : Use the splitlines() method to split the ini_str string into a list of substrings. The splitlines() method is a built-in Python method that splits a s
4 min read
Python - Replace delimiter
Given List of Strings and replacing delimiter, replace current delimiter in each string. Input : test_list = ["a, t", "g, f, g", "w, e", "d, o"], repl_delim = ' ' Output : ["a t", "g f g", "w e", "d o"] Explanation : comma is replaced by empty spaces at each string. Input : test_list = ["g#f#g"], repl_delim = ', ' Output : ["g, f, g"] Explanation :
7 min read
Python - Convert delimiter separated Mixed String to valid List
Given a string with elements and delimiters, split elements on delimiter to extract with elements ( including containers). Input : test_str = "6*2*9*[3, 5, 6]*(7, 8)*8*4*10", delim = "*" Output : [6, 2, 9, [3, 5, 6], (7, 8), 8, 4, 10] Explanation : Containers and elements separated using *. Input : test_str = "[3, 5, 6]*(7, 8)*8*4*10", delim = "*"
10 min read
Python - Convert List to delimiter separated String
In Python, lists are useful data structures that allow us to store collections of elements. Often, there arises a need to convert a list into a single string, where each element is separated by a delimiter of our choice. In this article, we will explore how to convert a list to a delimiter-separated string and demonstrate practical use cases for th
5 min read
Python - Convert Delimiter separated list to Number
Given a String with delimiter separated numbers, concatenate to form integer after removing delimiter. Input : test_str = "1@6@7@8", delim = '@' Output : 1678 Explanation : Joined elements after removing delim "@"Input : test_str = "1!6!7!8", delim = '!' Output : 1678 Explanation : Joined elements after removing delim "!" Method #1 : Using loop + s
6 min read
Python - Segregate elements by delimiter
Given a list of Strings, segregate each string by delimiter and output different lists for prefixes and suffixes. Input: test_list = ["7$2", "8$5", "9$1"], delim = "$" Output : ['7', '8', '9'], ['2', '5', '1'] Explanation Different lists for prefixes and suffixes of "$" Input test_list = ["7*2", "8*5", "9*1"], delim = "*" Output : ['7', '8', '9'],
6 min read
Python - Construct dictionary Key-Value pairs separated by delimiter
Given a String with key-value pairs separated by delim, construct a dictionary. Input : test_str = 'gfg#3, is#9, best#10', delim = '#' Output : {'gfg': '3', 'is': '9', 'best': '10'} Explanation : gfg paired with 3, as separated with # delim. Input : test_str = 'gfg.10', delim = '.' Output : {'gfg': '10'} Explanation : gfg paired with 10, as separat
7 min read
Python - Concatenate Tuple elements by delimiter
Given a tuple, concatenate each element of tuple by delimiter. Input : test_tup = ("Gfg", "is", 4, "Best"), delim = ", " Output : Gfg, is, 4, Best Explanation : Elements joined by ", ". Input : test_tup = ("Gfg", "is", 4), delim = ", " Output : Gfg, is, 4 Explanation : Elements joined by ", ". Method #1 : Using list comprehension In this, we iterat
7 min read
Practice Tags :
three90RightbarBannerImg