Python - Selectively Split in Strings
Last Updated :
15 Apr, 2023
Sometimes, while working with Python strings, we may have to perform a split. Not sometimes, normal one, depending on deliminator but something depending upon programming constructs like elements, numbers, words etc and segregate them. Lets discuss a way in which this task can be solved.
Method : Using re.findall() A specific regex can be employed to perform this task. In this we construct regex using different elements like numbers, words punctuations etc.
Python3
# Python3 code to demonstrate working of
# Selective Split in Strings
# Using regex
import re
# initializing string
test_str = "print(\"geeks\");"
# printing original string
print("The original string is : " + test_str)
# Selective Split in Strings
# Using regex
res = re.findall('\d+\.\d+|\d+|\w+|[^a-zA-Z\s]', test_str)
# printing result
print("The splitted string is : " + str(res))
OutputThe original string is : print("geeks");
The splitted string is : ['print', '(', '"', 'geeks', '"', ')', ';']
Time Complexity: O(n)
Space Complexity: O(n)
Approach#2: Using a loop
this approach involves iterating over each character in the input string and building substrings based on the separators (", (, ), ;). The resulting substrings and separators are stored in a list and returned.
Algorithm
1. Define a list to store the resulting substrings and separators.
2. Define a variable to store the current substring being built.
3. Iterate over each character in the input string.
4. If the current character is a separator, add the current substring to the list and add the separator to the list.
5. Otherwise, append the current character to the current substring.
6. Add the final substring to the list.
7. Return the resulting list of substrings and separators.
Python3
def split_string(string):
substrings = []
current_substring = ''
for char in string:
if char in ['"', '(', ')', ';']:
if current_substring != '':
substrings.append(current_substring)
current_substring = ''
substrings.append(char)
else:
current_substring += char
if current_substring != '':
substrings.append(current_substring)
return substrings
string = 'print("geeks");'
print(split_string(string))
Output['print', '(', '"', 'geeks', '"', ')', ';']
Time Complexity: O(n), where n is the length of the input string, because we iterate over each character in the string once to split it.
Auxiliary Space: O(n), where n is the length of the input string, because we create a new list to store the resulting substrings and separators.
METHOD 3: Using re.split module
APPROACH:
In this approach, we use a regular expression to split the string based on either a delimiter ((, ), ", or ;) or a sequence of one or more word characters (\w+). The regular expression is enclosed in parentheses to capture the delimiters as separate items in the resulting list. The filter() function is used to remove the empty.
ALGORITHM:
Python3
import re
string = 'print("geeks");'
split_string = re.split(r'([\(\)"\;])|(\w+)', string)
# Removing the empty strings and None values from the list
split_string = list(filter(lambda x: x != '' and x is not None, split_string))
print(split_string) # ['print', '(', '"', 'geeks', '"', ')', ';']
Output['print', '(', '"', 'geeks', '"', ')', ';']
The time complexity of this approach is O(n)
The auxiliary space of this approach is O(n).
Similar Reads
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 - 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 - Uppercase Selective Substrings in String Given a String, perform uppercase of particular Substrings from List. Input : test_str = 'geeksforgeeks is best for cs', sub_list = ["best", "geeksforgeeks"] Output : GEEKSFORGEEKS is BEST for cs Explanation : geeksforgeeks and best uppercased. Input : test_str = 'geeksforgeeks is best for best', su
7 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
Python - Split String on vowels Given a String, perform split on vowels. Example: Input : test_str = 'GFGaBst' Output : ['GFG', 'Bst'] Explanation : a is vowel and split happens on that. Input : test_str = 'GFGaBstuforigeeks' Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']Explanation : a, e, o, u, i are vowels and split happens on th
5 min read
Python | Reverse Interval Slicing String Sometimes, while working with strings, we can have a problem in which we need to perform string slicing. In this, we can have a variant in which we need to perform reverse slicing that too interval. This kind of application can come in day-day programming. Let us discuss certain ways in which this t
4 min read
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 | Splitting string list by strings Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
3 min read
re.split() in Python The re.split() method in Python is used to split a string by a pattern (using regular expressions). It is part of the re-module, which provides support for working with regular expressions. This method is helpful when we need to split a string into multiple parts based on complex patterns rather tha
3 min read
Python | Exceptional Split in String 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
4 min read