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
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
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
Split String into List of characters in Python We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read
Python - Phrase removal in String Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
2 min read
Python - Extract range characters from String Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
4 min read
Reverse Alternate Characters in a String - Python Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and
3 min read