Change language

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

Python | Splitting operators in a string Python functions: Questions

Python | Splitting operators in a string split: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method