Skip to content
Related Articles

Related Articles

Python | Splitting operators in String

View Discussion
Improve Article
Save Article
  • Last Updated : 18 Sep, 2022
View Discussion
Improve Article
Save Article

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’]

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)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!