Reputation: 45
I want to separate the digits from characters and letters and add them to a list.
n = "1+22-3*4/5"
eq=list(n)
c=0
for i in eq:
if "*" in eq:
while "*" in eq:
c=eq.index("*")
eq[c-1]=float(eq[c-1])*float(eq[c+1])
del eq[c]
del eq[c]
print(eq)
if "/" in eq:
while "/" in eq:
c=eq.index("/")
eq[c-1]=float(eq[c-1])/float(eq[c+1])
del eq[c]
del eq[c]
print(eq)
if "+" in eq:
while "+" in eq:
c=eq.index("+")
eq[c-1]=float(eq[c-1])+float(eq[c+1])
del eq[c]
del eq[c]
print(eq)
if "-" in eq:
while "-" in eq:
c=eq.index("-")
eq[c-1]=float(eq[c-1])-float(eq[c+1])
del eq[c]
del eq[c]
print(eq)
print(n,"=",eq)
It can only append every digit in the list. The current output is ['1','+','2','2','-','3','*','4','/','5']
Upvotes: 1
Views: 270
Reputation: 15310
I suggest you process the characters of the string in order (for ch in str) and either (a) add them to your list; or (b) accumulate them into a number:
str = "1+22-3*4/5"
tokens = []
number = None
operators = "+-*/"
digits = "0123456789"
for ch in str:
if ch in operators:
if number is not None:
tokens.append(number)
tokens.append(ch)
continue
elif ch in digits:
if number is None:
number = ch
else:
number += ch
continue
else:
# what else could it be?
pass
# After loop, check for number at end
if number is not None:
tokens.append(number)
Upvotes: 0
Reputation: 4265
Some great solutions here using stdlib
, here's a pure python try:
i = "11+11*11"
def parser(i):
out = []
gram = []
for x in i:
if x.isdigit():
gram.append(x)
else:
out.append("".join(gram))
out.append(x)
gram = []
if gram:
out.append("".join(gram))
return out
parser(i) # ['11', '+', '11', '*', '11']
Upvotes: 1
Reputation: 106533
You can use itertools.groupby
with str.isdigit
as the key function:
from itertools import groupby
[''.join(g) for _, g in groupby(n, key=str.isdigit)]
This returns:
['1', '+', '22', '-', '3', '*', '4', '/', '5']
Upvotes: 4
Reputation: 1771
You could use a regular expression:
import re
s = "1+22-3*4/5"
re.split('(\W)', s)
['1', '+', '22', '-', '3', '*', '4', '/', '5']
Upvotes: 2