The Wayback Machine - https://web.archive.org/web/20241001032304/https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/
Open In App

Python – Avoid Last occurrence of delimiter

Last Updated : 05 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Python program to convert a list of strings with a delimiter to a list of tuple
Given a List containing strings with a particular delimiter. The task is to remove the delimiter and convert the string to the list of tuple. Examples: Input : test_list = ["1-2", "3-4-8-9"], K = "-" Output : [(1, 2), (3, 4, 8, 9)] Explanation : After splitting, 1-2 => (1, 2). Input : test_list = ["1*2", "3*4*8*9"], K = "*" Output : [(1, 2), (3,
7 min read
Python - Sort words separated by Delimiter
Given string of words separated by some delimiter. The task is to sort all the words given in the string Input : test_str = 'gfg:is:best:for:geeks', delim = "*" Output : best*for*geeks*gfg*is Explanation : Words sorted after separated by delim. Input : test_str = 'gfg:is:best', delim = "*" Output : best*gfg*is Explanation : Words sorted after separ
6 min read
Detecting Delimiter in Text using detect_delimiter in Python
Sometimes while working with a large corpus of text, we can have a problem in which we try to find which character is acting as a delimiter. This can be an interesting and useful utility while working with a huge amount of data and judging the delimiter. A way to solve this problem is discussed in this article using the Python library of detect_del
3 min read
Split a String by a Delimiter in Python
In Python Programming, the split() method is used to split a string into a list of substrings which is based on the specified delimiter. This method takes the delimiter as an argument and returns the list of substrings. Along with this method, we can use various approaches wot split a string by the specified delimiter in Python. In this article, we
2 min read
Python | Last occurrence of some element in a list
There are many ways to find out the first index of element in the list as Python in its language provides index() function that returns the index of first occurrence of element in list. But if one desires to get the last occurrence of element in list, usually a longer method has to be applied. Let's discuss certain shorthands to achieve this partic
4 min read
Python | Find last occurrence of substring
Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can find the last occurrence of substring in string in Py
8 min read
Python - Slice from Last Occurrence of K
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the task of performing characters stripping on the last occurrence of element. This can have applications in which data is involved. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + string slicing The combination of
3 min read
Python Program For Deleting Last Occurrence Of An Item From Linked List
Using pointers, loop through the whole list and keep track of the node prior to the node containing the last occurrence key using a special pointer. After this just store the next of next of the special pointer, into to next special pointer to remove the required node from the linked list. C/C++ Code # Python program to implement # the above approa
6 min read
How to read a CSV file to a Dataframe with custom delimiter in Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use th
3 min read
Python - Avoid Spaces in string length
Given a String, compute all the characters, except spaces. Input : test_str = 'geeksforgeeks 33 best' Output : 19 Explanation : Total characters are 19. Input : test_str = 'geeksforgeeks best' Output : 17 Explanation : Total characters are 17 except spaces. Method #1 : Using isspace() + sum() In this, we check for each character to be equal not to
6 min read
Avoid TLE in Python in Competitive Programming
Reasons behind getting TLE: It is slower compared to other programming languages.It offers slower Input/Output.It has a lower recursion depth which often gives TLE in recursion and graph problems. Tips to avoid TLE with Python: Convert to an Iterative Approach:Any problem of recursion can be converted to an iterative approach, so try to use the ite
4 min read
How To Avoid Notimplementederror In Python?
Python's object-oriented architecture and versatility let programmers create dependable and scalable applications. Nevertheless, developers frequently encounter the NotImplementedError, especially when working with inheritance and abstract classes. This article will define NotImplementedError, explain its causes, and provide guidance on how to avoi
4 min read
3 Rookie Mistakes to Avoid with Python Lists
We will see the 3 Rookie Mistakes To Avoid With Python Lists. We will discuss some general mistakes and solutions for Python Lists. 3 Rookie Mistakes to Avoid with Python ListsBelow are the 3 Rookie Mistakes To Avoid With Lists in Python: Mistake 1st: Modifying a List While Iterating Over ItOne common mistake is modifying a list while iterating ove
3 min read
7 Mistakes You Should Avoid While Building a Django Application
Django...We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications. A lot of common features
6 min read
Avoid these mistakes while preparing for the CAT Exam
The CAT exam is arguably the most important exam in India for students wanting to secure the coveted MBA seats in various management institutes of the country. This is obvious from the high level of competition with more than two lakh candidates competing for seats in various MBA programs such as Finance, Marketing, Operations, etc. and only 11 can
6 min read
How to avoid duplicate columns after join in PySpark ?
When working with PySpark, it's common to join two DataFrames. However, if the DataFrames contain columns with the same name (that aren't used as join keys), the resulting DataFrame can have duplicate columns. This is particularly relevant when performing self-joins or joins on multiple columns. Below, we discuss methods to avoid these duplicate co
2 min read
10 Strategies to Avoid Cyber Security Threats in 2024
In 2024, cybersecurity pitfalls are more sophisticated than ever. With digital transformation rapidly advancing, individuals and associations must stay vigilant to protect their data from cybercriminals. Table of Content 10 Strategies to Avoid Cyber Security Threats in 20241. UseMulti-Factor Authentication( MFA) 2. Implement Strong Password Policie
5 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Python program to remove Nth occurrence of the given word
Given a list of words in Python, the task is to remove the Nth occurrence of the given word in that list. Examples: Input: list - ["geeks", "for", "geeks"] word = geeks, N = 2 Output: list - ["geeks", "for"]Input: list - ["can", "you", "can", "a", "can" "?"] word = can, N = 1 Output: list - ["you", "can", "a", "can" "?"] Approach #1: By taking anot
8 min read
Python | Replace multiple occurrence of character by single
Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Naive Approach This method is a brute force approach
4 min read
Practice Tags :