7
$\begingroup$

Consider the following:

list={1,2,2,2,3};

I would like to replace all 2 with the string "Test". Replace[list,2->"Test"] does not do it.

Result must be: {1,"Test","Test","Test",3}.

$\endgroup$
0

3 Answers 3

9
$\begingroup$

You can use:

list /. {2 -> "Test"}

(* Out[]:= {1, "Test", "Test", "Test", 3} *)
$\endgroup$
4
  • 3
    $\begingroup$ Internally, a /. b becomes ReplaceAll[a,b] which by default, replaces all instances found. $\endgroup$
    – rcollyer
    Apr 19, 2012 at 17:00
  • $\begingroup$ I prefere this one at the moment, as you can replace different figures at the same time, e.g. list/.{1->"A",2->"X"}. I wounder whether Replace is able of that too? $\endgroup$
    – John
    Apr 19, 2012 at 17:01
  • 1
    $\begingroup$ @John It is: Replace[list, {1 -> "B", 2 -> "Test"}, {1}] $\endgroup$
    – Eli Lansey
    Apr 19, 2012 at 17:02
  • 2
    $\begingroup$ @John note, that once a match is found, it stops looking, and refuses to apply a sequence of replacements, e.g. a /. {a -> b, b -> c} returns b. But, you can use ReplaceRepeated (//.), instead. a //. {a -> b, b -> c} then returns c. $\endgroup$
    – rcollyer
    Apr 19, 2012 at 17:05
10
$\begingroup$

Replace by default works on the whole expression. You can add a level specification

list={1,2,2,2,3};
Replace[list,2->"Test", {1}]

Gives

{1, "Test", "Test", "Test", 3}
$\endgroup$
7
$\begingroup$

For example:

list = {1, 2, 2, 2, 3};
list /. {2 -> "test"}
If[# == 2, "test", #] & /@ list
Replace[list, 2 -> "test", 1]
ReplacePart[list, Position[list, 2] -> "test"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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