How can I convert the following sample string to a list in Mathematica?
a = "1,2,3,4,test*,,6,7" ToExpression[StringSplit[a, ","]]
I have a large file to load with a similar structure, and need to convert it in to a list, but the * at the end of test*, is messing things up!
Thanks for the help!
Apply ToExpression to each element of the list using Map (/@). And, for each element, check if it is a good syntax:
a = "1,2,3,4,test*,,6,7" b = If[SyntaxQ[#], ToExpression[#], #] & /@ StringSplit[a, ","]
In case the syntax is good, use ToExpression, otherwise return the original string.
a = {"1", "2", "3", "4", "test*", , "6", "7"}; If[StringMatchQ[#, NumberString],ToExpression[#],StringReplace[#, x__ ~~ "*" -> x]] & /@ DeleteCases[a, Null]
This will give the output:
{1, 2, 3, 4, "test", 6, 7}
Sorry if I wasn't clear in my question.
Let assume I have the following list (a) of text elements. Then how do I convert it to a list of normal elements, i.e. text and numbers?
a = {"1", "2", "3", "4", "test*", , "6", "7"} ToExpression[a]
My code above would produce errors, due to "test*" not being recognized.
The output I require is all elements as numbers, except test which should be the element "test".
Thanks.
Not sure if I understood the question correctly. If you want to convert strings to expressions, you can try this:
StringCases[a, x:DigitCharacter..:>ToExpression[x]]