2
$\begingroup$

I want to replace T1 with T2 if the list contains X (It's a string with something more) or else return unevaluated.

Input:list={{1,Y 25,T1},{2,Y 26 V, T1},{3, X 25 D, T1}}

Output:{{1,Y 25,T1},{2,Y 26 V, T1},{3, X 25 D, T2}}

I have tried this:

 If[MemberQ[{list}, "X"], Replace["T1" -> "T2"], Unevaluated[Sequence[]]] 
$\endgroup$
6
  • $\begingroup$ In your list, X is not a string, but a variable, correct? $\endgroup$ Commented Nov 17, 2015 at 16:13
  • $\begingroup$ It's a string (with something else), that's why I am having trouble. $\endgroup$ Commented Nov 17, 2015 at 16:16
  • $\begingroup$ So when I copy your input, it doesn't come as a string $\endgroup$ Commented Nov 17, 2015 at 16:17
  • $\begingroup$ Is every element of the list a string? $\endgroup$ Commented Nov 17, 2015 at 16:19
  • $\begingroup$ Maybe Replace[list, T1 -> T2, {2}]? $\endgroup$ Commented Nov 17, 2015 at 16:24

2 Answers 2

1
$\begingroup$
list = {{"1", "Y 25", "T1"}, {"2", "Y 26 V", "T1"}, {"3", "X 25 D", "T1"}}; If[StringContainsQ[ToString@#, "X"], # /. "T1" -> "T2", #] & /@ list (* {{"1", "Y 25", "T1"}, {"2", "Y 26 V", "T1"}, {"3", "X 25 D", "T2"}} *) 
$\endgroup$
0
$\begingroup$
Clear["Global`*"] list = {{"1", "Y 25", "T1"}, {"2", "Y 26 V", "T1"}, {"3", "X 25 D", "T1"}}; If[Or @@ StringContainsQ["X"][#], StringReplace["T1" -> "T2"][#], #] & /@ list 

{{"1", "Y 25", "T1"}, {"2", "Y 26 V", "T1"}, {"3", "X 25 D", "T2"}}

$\endgroup$
1
  • $\begingroup$ Note for OP: the StringReplace would also change "T1 r" to "T2 r" whereas a Replace["T1"->"T2"] as in the question would not. This might be desired, might not or might be irrelevant depending on the lists the code will be used for. $\endgroup$ Commented Apr 15, 2023 at 14:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.