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$ Commented 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$ Commented 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$ Commented Mar 22, 2021 at 15:12
  • $\begingroup$ Thank you very much for your answer! $\endgroup$ Commented 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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.