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!
sghuisman
(Sander Huisman)
2
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.
girishav
(Girish Arabale)
3
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]]
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.
girishav
(Girish Arabale)
5
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}