4
$\begingroup$

enter image description here

As you can see from the picture, when I use StringReplace function, the list is converted to a string. How can I get the list form back? And the String "-" is necessary (Cuz I just know one way to replace "->" to "-").

$\endgroup$
2
  • $\begingroup$ Please post code as text, not images. I think you want Subtract @@@ b3. But why are you using Rule to construct b3 if what you want is Subtract? $\endgroup$ Mar 22, 2021 at 15:02
  • $\begingroup$ I do not quit understand what you are trying to do, but to get a string back to an expression, you would use: ToExpression $\endgroup$ Mar 22, 2021 at 15:05

4 Answers 4

4
$\begingroup$

Post actual data and code rather than images.

Clear["Global`*"];

b1 = {a, b, c, d, e};

b2 = {1, 2, 3, 4, 5};

b3 = Thread[b1 -> b2];

b4 = StringReplace[ToString /@ b3, "->" -> "-"]

(* {"a - 1", "b - 2", "c - 3", "d - 4", "e - 5"} *)

Alternatively, without ever generating b3

b5 = ToString[#[[1]]] <> " - " <> ToString[#[[2]]] & /@ Transpose[{b1, b2}]

(* {"a - 1", "b - 2", "c - 3", "d - 4", "e - 5"} *)

The approaches produce identical results.

b4 === b5

(* True *)
$\endgroup$
2
  • 1
    $\begingroup$ b5 = MapThread[ ToString[#1] <> " - " <> ToString[#2] &, {b1, b2}] $\endgroup$ Mar 22, 2021 at 15:12
  • $\begingroup$ Thank you very much for your answer! $\endgroup$ Mar 22, 2021 at 15:19
2
$\begingroup$
b1 = {a, b, c, d, e};

b2 = {1, 2, 3, 4, 5};

Some more possibilities:

StringRiffle[#, "-"] & /@ Transpose[{b1, b2}]

{"a-1", "b-2", "c-3", "d-4", "e-5"}

Cases[Transpose[{b1, b2}], x : {_, _} :> StringRiffle[x, "-"]]

{"a-1", "b-2", "c-3", "d-4", "e-5"}

SequenceCases[Riffle[b1, b2], x : {_, _} :> StringRiffle[x, "-"]]

{"a-1", "b-2", "c-3", "d-4", "e-5"}

$\endgroup$
1
$\begingroup$

Yeah, I found the answer, the last line I should use b4 = StringReplace[ToString /@ b3, "->" -> "-"].

$\endgroup$
1
$\begingroup$
b1 = {a, b, c, d, e};

b2 = {1, 2, 3, 4, 5};

Using Thread and MapApply:

#1 <> " - " <> #2 & @@@ Map[ToString, Thread[{b1, b2}], {2}]

Result:

{"a - 1", "b - 2", "c - 3", "d - 4", "e - 5"}

$\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.