Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

up vote 5 down vote accepted

You can use:

list /. {2 -> "Test"}

(* Out[]:= {1, "Test", "Test", "Test", 3} *)
share|improve this answer
2  
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

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"]
share|improve this answer

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}
share|improve this answer

Your Answer

 
discard

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.