Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a list of strings representing different types of data

{{"gw12-26b-pl1", "63.6512", "0.0076", "--", "Al2O3", "%", "23.4002"},
 {"gw12-26b-pl3", "65.1182", "0.1257", "--", "SiO2", "ppm", "76.3388"}};

I want to convert the 'numerical strings' to expressions so that I can work with them. I want to end up with something like:

{{"gw12-26b-pl1", 63.6512, 0.0076, "--", "Al2O3", "%", 23.4002},
 {"gw12-26b-pl3", 65.1182, 0.1257, "--", "SiO2", "ppm", 76.3388}}

I tried to convert the whole list using ToExpression and then convert non-numeric elements back to strings but this doesn't work because it is trying to evaluate elements like gw12-26b-pl1as an expression.

Can anyone suggest an easy way to do this?

share|improve this question
up vote 7 down vote accepted

A way of doing the replacement not explicitly, but implicitly with a function is to define a function t, which converts a NumberString to the number and leaves the rest untouched. Giving t the attribute Listable and it can directly be applied on the list:

SetAttributes[t, {Listable}];
t[a_String /; StringMatchQ[a, NumberString]] := ToExpression[a];
t[a_] := a;

Now you have

t@{{"gw12-26b-pl1", "63.6512", "0.0076", "--", "Al2O3", "%", 
   "23.4002"}, {"gw12-26b-pl3", "65.1182", "0.1257", "--", "SiO2", 
   "ppm", "76.3388"}}
(* {{"gw12-26b-pl1", 63.6512, 0.0076, "--", "Al2O3", "%", 
  23.4002}, {"gw12-26b-pl3", 65.1182, 0.1257, "--", "SiO2", "ppm", 
  76.3388}} *)
share|improve this answer
Thanks! This solution is elegant because it works on nested lists. e.g. t@ {"67", "34d-45b", {"b", "27", {"ww", "11.1", {{"67.1"}, "aa", "3"}}}} – geordie May 20 '14 at 1:50
To speed up the code, you can use Internal`StringToDouble instead of ToExpression – Murta May 20 '14 at 1:52
@rasher I edited your answer and voted to undelete it. If you make your pattern restrict to strings, you don't get error messages when doing a ReplaceAll. – halirutan May 20 '14 at 2:07
@MikeHoneychurch here – Murta May 20 '14 at 3:30
@rasher It's the other way around, because I wrote my version as an addition to your answer. And yes, I can vote for undeletion no matter whether you deleted your answer. In the end I would respect your decision, but I hope you don't take the whole issue too hard that. It always happens, and especially me, that I give a solution which is specific to the OP's needs. Often the OP then decides that a more general version was required. That's SE live I guess. – halirutan May 20 '14 at 8:43

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.