Group Abstract Group Abstract

Message Boards Message Boards

0
|
16.8K Views
|
4 Replies
|
1 Total Like
View groups...
Share
Share this post:

Convert string to a list with ToExpression with text?

Posted 9 years ago
POSTED BY: Priyan Fernando
4 Replies
Posted 9 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
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 9 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