Python | Splitting operators in a string



Method # 1: Using re.split()
This task can be accomplished using the split function provided by the Python regex library that can split string under certain conditions, and in this case — all numbers and operators.

# Python3 code to demonstrate how it works
# Line splitting operators
# Using re.split ()

import re

 
# initialization string

test_str = "15 + 22 * ​​3-4 / 2 "

  
# print original line

print ( "The original string is:" + str (test_str))

  
# Using re.split ()
# Line splitting operators

res = re.split (r `(D)` , test_str)

  
# print 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 can also do the same task as the above function. It can also support decimal numbers as additional functionality.

# Python3 code to demonstrate how it works
# Line splitting operators
# Using re.findall ()

import re

 
# initializing string

test_str = "15 + 22.6 * 3-4 / 2 "

  
# print original line

print ( "The original string is:" + str < / code> (test_str))

 
# Using re.findall ()
# Line splitting operators

res = re.findall (r `[0-9.] + | [^ 0-9.] + ` , test_str)

  
# print 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`]