Open In App

Python | Exceptional Split in String

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

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

  1. Initialize a list patterns with the patterns that we want to exclude from the split. In this case, the patterns are ‘, ‘ and ‘, ‘(.
  2. 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.
  3. 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.
  4. 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))


Output

The 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

Python | Exceptional Conditions Testing in Unit Tests
This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used. Code #1 : Testing that a function raised a ValueError exception import unittest # A simple function to illustrate def parse_int(s): return int(s) class TestConversion(unittest.TestCase): def test_bad_int(se
2 min read
Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Python program to split and join a string
Python program to Split a string based on a delimiter and join the string using another delimiter. Splitting a string can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files). We use s
7 min read
Python | Split given string into equal halves
Sometimes, we need to simply divide the string into two equal halves. This type of application can occur in various domain ranging from simple programming to web development. Let's discuss certain ways in which this can be performed. Method #1 : Using list comprehension + String slicing This is the naive method to perform this particular task. In t
4 min read
Split a string in equal parts (grouper in Python)
Grouper recipe is an extended toolset made using an existing itertool as building blocks. It collects data into fixed-length chunks or blocks. Existing Itertools Used: izip_longest(*iterables[, fillvalue]) : Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with
2 min read
Python | Split string into list of characters
Given a string, write a Python program to split the characters of the given string into a list using Python. In this article, we will explore various methods to split a string into a list of characters, allowing developers to manipulate and work with individual characters efficiently. Input: geeks Output : ['g', 'e', 'e', 'k', 's'] Input: Word Outp
4 min read
Python | Split string in groups of n consecutive characters
Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character. Examples: Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'org', 'eek', 's'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567] Method #1: Using list comprehension C/C++ Code # Python
2 min read
Python | String Split including spaces
The problems and at the same time applications of list splitting are quite common while working with python strings. The spaces usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let's discuss certain ways in which this problem can be solved. Method #1: Using spli
4 min read
Python | Split CamelCase string to individual strings
Given a string in a camel-case, write a Python program to split each word in the camel case string into individual strings. Examples: Input : "GeeksForGeeks" Output : ['Geeks', 'For', 'Geeks'] Input : "ThisIsInCamelCase" Output : ['This', 'Is', 'In', 'Camel', 'Case'] Method #1: Naive Approach A naive or brute-force approach to split CamelCase strin
4 min read
Python | Split string on Kth Occurrence of Character
Many problems of the split have been dealt with in the past, but sometimes, one can also encounter this problem in which we need to split the string on the Kth occurrence of a character. Let's discuss certain ways in which this problem can be solved. Method #1 : Using split() + join() The split and join method can perform this particular task. In t
6 min read
Practice Tags :