some_guy
some_guy

Reputation: 43

Split line by +-*/() (as delimeters) without omitting them in python

Good day.

I'm trying to split (tokenize) a string like

(22+33)* 44 / 300

and get output like

['(','22','+','33',')','*','44','/','300']

so far I tried to use

infix = input("Enter the infix notation : ")
infix = re.split(r'[+-/*()]', infix)

but it omits delimiters and creates '' elements at list.

Upvotes: 1

Views: 101

Answers (3)

John Kugelman
John Kugelman

Reputation: 361919

Instead of splitting the string on delimiters, I recommend just searching for the tokens.

>>> re.findall(r'\d+|[-+/*()]', infix)
['(', '22', '+', '33', ')', '*', '44', '/', '300']

Upvotes: 3

vks
vks

Reputation: 67988

(?=\+|-|\/|\*|\(|\)|\b\d+\b)

Try this.

use y= re.sub(r"(?=\+|-|\/|\*|\(|\)|\b\d+\b)","\n",x)

print y.split("\n")

.

See demo.

http://regex101.com/r/kK4cB5/1

Upvotes: 0

neiesc
neiesc

Reputation: 653

re.split

infix = input("Enter the infix notation : ")
infix = re.split(r'([+-/*()])', infix)

Upvotes: 6

Related Questions