Python | Exceptional Split in String
Last Updated :
08 Apr, 2023
Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should not be enclosed by brackets. Lets discuss certain ways in which this task can be performed.
Method #1: Using loop + strip() This is brute force way in which we perform this task. In this we construct each element of list as words in String accounting for brackets and comma to perform split.
Python3
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using loop + split()
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using loop + split()
temp = ''
res = []
check = 0
for ele in test_str:
if ele == '(':
check += 1
elif ele == ')':
check -= 1
if ele == ', ' and check == 0:
if temp.strip():
res.append(temp)
temp = ''
else:
temp += ele
if temp.strip():
res.append(temp)
# printing result
print("The string after exceptional split : " + str(res))
Output : The original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']
Method #2: Using regex() This is yet another way in which this task can be performed. In this, we use a regex instead of manual brute force logic for brackets comma and omit that from getting split.
Python3
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using regex()
import re
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using regex()
res = re.split(r', (?!\S\)|\()', test_str)
# printing result
print("The string after exceptional split : " + str(res))
Output : The original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using str.split() and list comprehension
- Initialize a list patterns with the patterns that we want to exclude from the split. In this case, the patterns are ', ' and ', '(.
- Use the split() method of the string object to split the string into a list of substrings based on the delimiter ', '. Store the resulting list in a variable split_str.
- Use a list comprehension to iterate over each substring in split_str and check if it matches any pattern in patterns. If it does, join it with the next substring in split_str. If it doesn't, add it to a new list res_list.
- Return the res_list as the result.
Python3
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using str.split() and list comprehension
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using str.split() and list comprehension
patterns = [', ', ', (' ]
split_str = test_str.split(', ')
res_list = [split_str[0]]
for i in range(1, len(split_str)):
if any(split_str[i-1].endswith(p) for p in patterns):
res_list[-1] += ', ' + split_str[i]
else:
res_list.append(split_str[i])
# printing result
print("The string after exceptional split : " + str(res_list))
OutputThe original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', 'is', '(best', 'for)', 'geeks']
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.
Similar Reads
Split and join a string in Python The goal here is to split a string into smaller parts based on a delimiter and then join those parts back together with a different delimiter. For example, given the string "Hello, how are you?", you might want to split it by spaces to get a list of individual words and then join them back together
3 min read
Python | Split given string into equal halves We are given a string, we need to split it into two halves. If the string has an odd length, the first half should be longer by one character.Using String Slicing String Slicing is the efficient approach which splits the string at the midpoint. If the string length is odd, the first half automatical
3 min read
Python | Split flatten String List Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
7 min read
Python - Split Strings on Prefix Occurrence Given a list of Strings, perform string split on the occurrence of prefix. Input : test_list = ["geeksforgeeks", "best", "geeks", "and"], pref = "geek" Output : [['geeksforgeeks', 'best'], ['geeks', 'and']] Explanation : At occurrence of string "geeks" split is performed. Input : test_list = ["good"
7 min read
Python - String Split including spaces String splitting, including spaces refers to breaking a string into parts while keeping spaces as separate elements in the result.Using regular expressions (Most Efficient)re.split() function allows us to split a string based on a custom pattern. We can use it to split the string while capturing the
3 min read
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
Python - Double Split String to Matrix Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix. Examples: Input : test_str = 'Gfg,best*for,all*geeks,and,CS', row_splt = "*", ele_splt = "," Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS
6 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
2 min read
Python - Split a String by Custom Lengths Given a String, perform split of strings on the basis of custom lengths. Input : test_str = 'geeksforgeeks', cus_lens = [4, 3, 2, 3, 1] Output : ['geek', 'sfo', 'rg', 'eek', 's'] Explanation : Strings separated by custom lengths.Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeks
2 min read
Python - Split String on all punctuations Given a String, Split the String on all the punctuations. Input : test_str = 'geeksforgeeks! is-best' Output : ['geeksforgeeks', '!', 'is', '-', 'best'] Explanation : Splits on '!' and '-'. Input : test_str = 'geek-sfo, rgeeks! is-best' Output : ['geek', '-', 'sfo', ', ', 'rgeeks', '!', 'is', '-', '
3 min read