How to NOT a specific pattern?

been going around in cirlces on this:

{1/3, 1, 0.22, 3, "v", 4} /. _?NumericQ -> "999"

Now I'm trying to replace everything that is not a number; is there a way to do this? using Not or Except perhaps...I've tried but I must be getting the syntax wrong!

If you are going to replace elements of a list, do not use ReplaceAll. Use Replace, which is the appropriate function for that task.

Replace[list, Except[_?NumericQ] :> "non-numeric", {1}]


The 3rd argument, {1}, indicates that only elements of the list ("1st level") are to be replaced, not the list itself.

If you were to use ReplaceAll, it would replace the entire list, as it does not match _?NumericQ. An over-use of ReplaceAll out of convenience (/. shorthand) or lack of awareness causes a lot of bugs in Mathematica code. I strongly suggest sticking to Replace unless you know you need ReplaceAll.

• Good answer. To understand a bit more, try replacing Except by Identity in the above to see the difference. The trick here, for me at least, is understanding where to put the Blank (i.e the _). – PaulCommentary Jun 30 at 17:31

By 1) Using Replace with a level spec so we don't replace the whole list but the elements, and 2) using a Composition (short form @*) of Not with NumericQ:

Replace[{1/3, 1, 0.22, 3, "v", 4}, _?(Not@*NumericQ) -> "999", {1}]


This is not new answer, just pulls together many of the responses in a consistent format, showing the experiments tried.

p1 = _?( Not @* NumericQ);

p2 = _? (Not @ NumericQ[#] &);

p3 = Except[_?NumericQ];

p4 = Except[x_ /; NumericQ[x]];

Replace[lis, p1 -> "999", {1}]

{1/3, 1, 0.22, 3, "999", 4}

Replace[lis, p2 -> "999", {1}]

{1/3, 1, 0.22, 3, "999", 4}

Replace[lis, p3 -> "999", {1}]

{1/3, 1, 0.22, 3, "999", 4}

Replace[lis, p4 -> "999", {1}]

{1/3, 1, 0.22, 3, "999", 4}