7

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}.

Ajasja
  • 13,634
  • 2
  • 46
  • 104
John
  • 4,361
  • 1
  • 26
  • 41

3 Answers3

10

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}
Rojo
  • 42,601
  • 7
  • 96
  • 188
9

You can use:

list /. {2 -> "Test"}

(* Out[]:= {1, "Test", "Test", "Test", 3} *)
Eli Lansey
  • 7,499
  • 3
  • 36
  • 73
  • 3
    Internally, a /. b becomes ReplaceAll[a,b] which by default, replaces all instances found. – rcollyer Apr 19 '12 at 17:00
  • 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? – John Apr 19 '12 at 17:01
  • 1
    @John It is: Replace[list, {1 -> "B", 2 -> "Test"}, {1}] – Eli Lansey Apr 19 '12 at 17:02
  • 2
    @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. – rcollyer Apr 19 '12 at 17:05
7

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"]
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453