Python | Rear stray character String split
Last Updated :
13 Apr, 2023
Python3
# Python3 code to demonstrate working of
# Rear stray character String split
# Using list comprehension
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using list comprehension
res = [word.strip() for word in test_str.split(',')][:-1]
# printing result
print("The evaluated result is : " + str(res))
OutputThe original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
Sometimes, while working with Python Strings, we can have problem in which we need to split a string. But sometimes, we can have a case in which we have after splitting a blank space at rear end of list. This is usually not desired. Lets discussed ways in which this can be avoided.
Method #1: Using split() + rstrip() The combination of above functions can be used to solve this problem. In this, we remove the stray character from the string before split(), to avoid the empty string in split list.
Python3
# Python3 code to demonstrate working of
# Rear stray character String split
# Using split() + rstrip()
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using split() + rstrip()
res = test_str.rstrip(', ').split(', ')
# printing result
print("The evaluated result is : " + str(res))
Output : The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
The time complexity of this program is O(n), where n is the length of the input string.
The auxiliary space complexity of this program is O(n), where n is the length of the input string.
Method #2: Using split() The use of rstrip() can be avoided by passing additional arguments while performing the split().
Python3
# Python3 code to demonstrate working of
# Rear stray character String split
# Using split()
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using split()
res = test_str.split(', ')[0:-1]
# printing result
print("The evaluated result is : " + str(res))
Output : The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
Time Complexity: O(n) -> (string split)
Auxiliary Space: O(n)
Method #3: Using regular expressions.
This program takes a string, removes the trailing comma and any whitespace characters after it, and then splits the string into a list of substrings using regular expressions. Finally, it prints the list of substrings.
Step-by-step approach:
- Import the re module
- Initialize the string
- Use re.split() to split the string by the comma followed by any number of whitespace characters and discard the last element
- Print the result
Below is the implementation of the above approach:
Python3
import re
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using regular expressions
res = re.split(',\s*', test_str)[:-1]
# printing result
print("The evaluated result is : " + str(res))
OutputThe original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), because the re.split() method creates a list of substrings, which uses additional memory.
Method #4: Using numpy:
Algorithm:
- Import numpy as np
- Initialize string test_str
- Print the original string
- Use numpy.split() to split the string
- Convert the result to list using tolist()
- Print the result
Python3
import numpy as np
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using numpy.split()
res = np.array(test_str.split(', ')).astype(str)
res = np.split(res, [len(res) - 1])[0].tolist()
# printing result
print("The evaluated result is : " + str(res))
#This code is contributed by Jyothi pinjala
Output:
The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
Time Complexity:
The time complexity of the code is O(n), where n is the length of the input string.
Auxiliary Space:
The space complexity of the code is O(n), where n is the length of the input string. This is because we are using the numpy library which requires additional memory space to store the array.
Method 5: Using List Comprehension
Step-by-step approach:
- Initialize the input string test_str.
- Use the list comprehension to split the string at commas and remove any whitespace before or after each word.
- Use slicing to remove the last element of the resulting list, which will be an empty string due to the trailing comma in the original string.
- Store the resulting list of words in the variable res.
- Print the original string and the resulting list.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Rear stray character String split
# Using list comprehension
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using list comprehension
res = [word.strip() for word in test_str.split(',')][:-1]
# printing result
print("The evaluated result is : " + str(res))
OutputThe original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), for the resulting list.
Similar Reads
Python | K Character Split String
The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Letâs discuss certain
4 min read
Splitting String to List of Characters - Python
We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python.Using list()The simplest way to split a string in
2 min read
Splitting String to List of Characters - Python
The task of splitting a string into a list of characters in Python involves breaking down a string into its individual components, where each character becomes an element in a list. For example, given the string s = "GeeksforGeeks", the task is to split the string, resulting in a list like this: ['G
3 min read
Remove Special Characters from String in Python
When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Python - Right and Left Shift characters in String
In string manipulation tasks, especially in algorithmic challenges or encoding/decoding scenarios, we sometimes need to rotate (or shift) characters in a string either to the left or right by a certain number of positions.For example, let's take a string s = "geeks" and we need to perform a left and
3 min read
Split String of list on K character in Python
In this article, we will explore various methods to split string of list on K character in Python. The simplest way to do is by using a loop and split().Using Loop and split()In this method, we'll iterate through each word in the list using for loop and split it based on given K character using spli
2 min read
Reverse Sort a String - Python
The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string "geeksforgeeks", the characters will be sorted from highest to lowest, resulting in a new string like "ssrokkggfeeeee". Let's understand different methods to pe
2 min read
Python - Remove Rear K characters from String List
Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
5 min read
Python - Reversed Split Strings
In Python, there are times where we need to split a given string into individual words and reverse the order of these words while preserving the order of characters within each word. For example, given the input string "learn python with gfg", the desired output would be "gfg with python learn". Let
3 min read
Python | Split by repeating substring
Sometimes, while working with Python strings, we can have a problem in which we need to perform splitting. This can be of a custom nature. In this, we can have a split in which we need to split by all the repetitions. This can have applications in many domains. Let us discuss certain ways in which t
5 min read