How do make a split on a string at a few different places? For example i wanna make a split on 5*4+1-1+3 to put all the numbers in a list. How do i do that?
Split() [solved with re.split]
Collapse
This topic is closed.
X
X
-
Tags: None
-
Geos, Please use code tags so your post looks like this:Originally posted by GeosHi,
This should do the job although I don't believe it is the best solution.
a = "1+2-3+5-6*8"
z = []
for x in a:
try :
int(x)
z.append(x)
except:
pass
print z
greetz Geos
Otherwise, it is very hard to use. Thanks,Code:a = "1+2-3+5-6*8" z = [] for x in a: try : int(x) z.append(x) except: pass print z
BartonComment
-
This is VERY cool! I've used the re module, but hadn't come across this usage. Thanks Fredrik!Originally posted by fuffensYou can use a regular expression to split the string. You still have to go through the list to convert to integers as in the previous example though.
Best regardsCode:import re re.split('[*+-]', '5*4+1-1+3')
/Fredrik
BartonComment
-
Here is a possible solution...
-kudosCode:for a in "5*4+1-1+3".split("*"): for b in a.split("+"): for c in b.split("-"): print c
Originally posted by MaxLindquistHow do make a split on a string at a few different places? For example i wanna make a split on 5*4+1-1+3 to put all the numbers in a list. How do i do that?Comment
Comment