I got the following problem I don't know how to solve or if it's at all possible to solve(I'm quite new to Mathematica and don't have an IT background, so please explain slowly if possible:))
I'm trying to convert a simple string which I imported from a homepage into a list of numbers. The string looks for example the following:
{"1,2,3,5,10,12,13,17,26,30,32,41,42,43,113,115,121,125"}
Mathematica sees this as one string, this is important, not as a list of strings. (I used the head function to check that)
My question: is it possible to convert this one string into a list of numbers so that each number in the string above is recognized as an individual element and can be calculated with?
Another important note: these strings don't all contain the same amount of numbers, a couple of them are shorter than other ones.
Is there any way I can convert these different strings into lists of numbers?
Answer
str = {"1,2,3,5,10,12,13,17,26,30,32,41,42,43,113,115,121,125"}
Flatten@ToExpression@StringSplit[str, ","]
Short explanation:
After executing StringSplit
you get a list of separated "StringNumbers" like
{{"1", "2", ... "125"}}
ToExpression
converts these "StringNumbers" to Integers. Flatten
removes the outermost brackets. You can even omit Flatten
by looking at gpap's comment. This works for lists of varying lengths and also for different number types.
EDIT
To also answer the question in your comment:
eq = {{"1", "3", "5", "6"}, {"1", "2", "4", "7"}, {"1", "3"}};
ToExpression[Flatten /@ Map[StringSplit[#, ","] &, eq]]
Comments
Post a Comment