Open In App

Python | Splitting operators in String

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

Sometimes we have a source string to have certain mathematical statement for computations and we need to split both the numbers and operators as a list of individual elements. Let’s discuss certain ways in which this problem can be performed. 

Method #1 : Using re.split() This task can be solved using the split functionality provided by Python regex library which has power to split the string according to certain conditions and in this case all numbers and operators. 

Python3




# Python3 code to demonstrate working of
# Splitting operators in String
# Using re.split()
import re
 
# initializing string
test_str = "15 + 22 * 3-4 / 2"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using re.split()
# Splitting operators in String
res = re.split(r'(\D)', test_str)
 
# printing result
print("The list after performing split functionality : " + str(res))


Output : 

The original string is : 15+22*3-4/2 The list after performing split functionality : [’15’, ‘+’, ’22’, ‘*’, ‘3’, ‘-‘, ‘4’, ‘/’, ‘2’]

Time Complexity: O(n) where n is the length of the input string.

Auxiliary Space: O(n)

Method #2 : Using re.findall() This Python regex library function also can perform the similar task as the above function. It can also support decimal numbers as additional functionality. 

Python3




# Python3 code to demonstrate working of
# Splitting operators in String
# Using re.findall()
import re
 
# initializing string
test_str = "15 + 22.6 * 3-4 / 2"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using re.findall()
# Splitting operators in String
res = re.findall(r'[0-9\.]+|[^0-9\.]+', test_str)
 
# printing result
print("The list after performing split functionality : " + str(res))


Output : 

The original string is : 15+22.6*3-4/2 The list after performing split functionality : [’15’, ‘+’, ‘22.6’, ‘*’, ‘3’, ‘-‘, ‘4’, ‘/’, ‘2’]

Method #3: Using split() method

Python3




# Python3 code to demonstrate working of
# Splitting operators in String
 
# initializing string
test_str = "15 + 22.6 * 3-4 / 2"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Splitting operators in String
op="+-*/"
res=""
for i in test_str:
    if i in op:
        res+="@"+i+"@"
    else:
        res+=i
res=res.split("@")
# printing result
print("The list after performing split functionality : " + str(res))


Output

The original string is : 15 + 22.6 * 3-4 / 2
The list after performing split functionality : ['15 ', '+', ' 22.6 ', '*', ' 3', '-', '4 ', '/', ' 2']

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

Approach#4: Using while loop

this approach is a simple algorithm that involves iterating through the input string character by character, identifying operators and operands, and storing them in a list

Algorithm

1. Initialize an empty list to store the operators and operands
2. Traverse through the input string character by character
3. If the current character is an operator (+, -, *, /), append it to the list
4. If the current character is a digit, read the entire number and append it to the list
5. Return the list

Python3




def split_operators(input_str):
    operators_and_operands = []
    i = 0
    while i < len(input_str):
        if input_str[i] in ('+', '-', '*', '/'):
            operators_and_operands.append(input_str[i])
            i += 1
        elif input_str[i].isdigit():
            start = i
            while i < len(input_str) and input_str[i].isdigit():
                i += 1
            operators_and_operands.append(input_str[start:i])
        else:
            i += 1
    return operators_and_operands
 
input_str = '15+22*3-4/2'
print(f"The original string is: {input_str}")
print(f"The list after performing split functionality: {split_operators(input_str)}")


Output

The original string is: 15+22*3-4/2
The list after performing split functionality: ['15', '+', '22', '*', '3', '-', '4', '/', '2']

Time Complexity: O(n), wherer n is the length of string
Auxiliary Space: O(n), where n is length of string

Approach#5: Using reduce():

  1. Define the input string test_str and the operator string op.
  2. Apply the reduce function to the test_str input string using a lambda function as a reducer.
  3. The lambda function takes two arguments: s, which is the accumulated result so far, and c, which is the current character in the input string.
  4. If the current character c is an operator (i.e., it is in the operator string op), then use re.split function to split the accumulated result s into a list, where the delimiter is the current operator character c. The delimiter is enclosed in square brackets to capture it as a separate element in the resulting list. The re.escape function is used to escape any special characters in the operator string op to avoid errors. Finally, re.split returns a list of substrings split using the delimiter.
  5. If the current character c is not an operator, then the accumulated result s is returned as is.
  6. The reduce function returns a list of substrings and/or operators.
  7. Filter out any empty strings from the resulting list.
  8. Print the resulting list.
     

Python3




import re
from functools import reduce
 
test_str = "15 + 22.6 * 3-4 / 2"
op = "+-*/"
 
res = reduce(lambda s, c: re.split('([' + re.escape(op) + '])', ''.join(s)) if c in op else s, test_str, test_str)
res = [i for i in res if i != '']
 
print("The list after performing split functionality : " + str(res))
#This code is contributed by Jyothi pinjala


Output

The list after performing split functionality : ['15 ', '+', ' 22.6 ', '*', ' 3', '-', '4 ', '/', ' 2']

The time complexity :O(n log n), where n is the length of the input string test_str. The reduce function needs to traverse the input string test_str once, and each call to re.split has a time complexity of O(log n), where n is the length of the accumulated string s.

The space complexity : O(n), where n is the length of the input string test_str. This is because the reduce function creates a list of substrings and/or operators, and the resulting list needs to be stored in memory. The filter operation creates a new list, but this list is smaller than the original list and can be ignored for the purpose of space complexity analysis.

Approach#6: Using numpy:

Algorithm:

  1. Convert the input string to a numpy array of characters.
  2. Define a list of operators to split on.
  3. Use the np.isin() method to find the indices where operators occur in the array.
  4. Initialize a list to hold the operators and operands.
  5. Loop over the operator indices and extract the operands and operators, adding them to the list.
  6. Add the last operand to the list.
  7. Remove any empty strings from the list.
  8. Return the list of operators and operands.

Python3




import numpy as np
 
def split_operators(input_str):
    # convert input string to numpy array of characters
    chars = np.array(list(input_str))
     
    # define operators to split on
    operators = ['+', '-', '*', '/']
     
    # find indices where operators occur
    operator_indices = np.where(np.isin(chars, operators))[0]
     
    # initialize list to hold operators and operands
    operators_and_operands = []
     
    # loop over operator indices to extract operators and operands
    start = 0
    for index in operator_indices:
        if index > start:
            operand = ''.join(chars[start:index])
            operators_and_operands.append(operand)
        operators_and_operands.append(chars[index])
        start = index + 1
     
    # add last operand to list
    operand = ''.join(chars[start:])
    operators_and_operands.append(operand)
     
    # remove empty strings from list
    operators_and_operands = list(filter(lambda x: x != '', operators_and_operands))
     
    return operators_and_operands
 
input_str = '15+22*3-4/2'
print(f"The original string is: {input_str}")
print(f"The list after performing split functionality: {split_operators(input_str)}")
#This code is contributed by Rayudu.


Output:

The original string is: 15+22*3-4/2
The list after performing split functionality: ['15', '+', '22', '*', '3', '-', '4', '/', '2']

Time Complexity: The algorithm uses a single loop to extract operators and operands, so the time complexity is O(n), where n is the length of the input string.

Space Complexity: The algorithm uses a numpy array to hold the characters of the input string, so the space complexity is O(n), where n is the length of the input string. The algorithm also creates a list to hold the operators and operands, so the additional space complexity is O(k), where k is the number of operators and operands in the input string. Therefore, the total space complexity is O(n + k).



Similar Reads

Python | Splitting string to list of characters
Sometimes we need to work with just the lists and hence strings might need to be converted into lists. It has to be converted in list of characters for certain tasks to be performed. This is generally required in Machine Learning to preprocess data and text classifications. Let's discuss certain ways in which this task is performed. Method #1: Usin
5 min read
Python | Splitting string to list of characters
Sometimes we get a string and we need to split it into the individual processing. This is quite a common utility and has application in many domains, be it Machine Learning or Web Development. Having shorthands to it can be helpful. Let's discuss certain ways in which this can be done. Method #1 : Using list() This is the simplest way to achieve th
2 min read
Python | Splitting list on empty string
Sometimes, we may face an issue in which we require to split a list to list of list on the blank character sent as deliminator. This kind of problem can be used to send messages or can be used in cases where it is desired to have list of list of native list. Let's discuss certain ways in which this can be done. Method #1 : Using index() and list sl
4 min read
Python | Splitting Text and Number in string
Sometimes, we have a string, which is composed of text and number (or vice-versa), without any specific distinction between the two. There might be a requirement in which we require to separate the text from the number. Let's discuss certain ways in which this can be performed. Method #1 : Using re.compile() + re.match() + re.groups() The combinati
7 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 solve this particular problem. Method : Using loop + i
3 min read
Splitting and Merging Channels with Python-OpenCV
In this article, we will learn how to split a multi-channel image into separate channels and combine those separate channels into a multi-channel image using OpenCV in Python. To do this, we use cv2.split() and cv2.merge() functions respectively. Image Used: Splitting Channels cv2.split() is used to split coloured/multi-channel image into separate
2 min read
Splitting stereo audio to mono with PyDub
Splitting a stereo audio file into multiple mono audio files is very useful if you are trying to process or transcribe the stereo audio files. This is because stereo audio has 2 audio sources on different channels which makes it very hard to process the file. Splitting the stereo audio file into mono audio files makes this job easier. For this arti
2 min read
Python3 Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
PySpark - Random Splitting Dataframe
In this article, we are going to learn how to randomly split data frame using PySpark in Python. A tool created by Apache Spark Community to use Python with Spark altogether is known as Pyspark. Thus, while working for the Pyspark data frame, Sometimes we are required to randomly split that data frame. In this article, we are going to achieve this
7 min read
Splitting Arrays in NumPy
NumPy arrays are an essential tool for scientific computing. However, at times, it becomes necessary to manipulate and analyze specific parts of the data. This is where array splitting comes into play, allowing you to break down an array into smaller sub-arrays, making the data more manageable. It is similar to slicing but on a larger scale. NumPy
6 min read
Practice Tags :