Message Boards Message Boards

0
|
12219 Views
|
4 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Convert string to a list with ToExpression with text?

Posted 7 years ago

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!

POSTED BY: Priyan Fernando
4 Replies
Posted 7 years ago

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]]
POSTED BY: Girish Arabale

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.

POSTED BY: Sander Huisman

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.

POSTED BY: Priyan Fernando
Posted 7 years ago
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}
POSTED BY: Girish Arabale
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract