# Turning numbers embedded in deeply nested lists into strings [closed]

This must have a simple answer, but I cannot think of it. I want to take the numbers in a list such as:

{1,{2,{{3,4},{5,6}},7,8}

into strings. ToString will turn the whole list into a string. And mapping cannot be done either, or I fail to see how to use it. Somehow, trying to replace using:

x_Integer->ToString[x]

doesn’t work (it turns the x into a string). This must be elementary, but I just can’t think of how to do this. Your help will be appreciated.

• Use :>, not ->. – J. M.'s technical difficulties May 27 at 20:08
• @J.M. Thank you, this works. I have a follow up question, which I hesitate to ask as a separate question. How do I replace each of the individual strings that arise from the operation you just indicated (or the one in the response below) with the concatenation of a string prefix and the stringed number. It seems my use of StringReplace is defective. If necessary I will edit the question. – EGME May 27 at 20:32
• @J.M. I can use what you suggested to do both things at once, but for specific reasons, I want to accomplish the second bit in a separate step. – EGME May 27 at 20:36

l = {1, {2, {{3, 4}, {5, 6}}, 7, 8}};
result=IntegerString[l]


{"1",{"2",{{"3","4"},{"5","6"}},"7","8"}}

Per your comment question, either map on result, or just combine into one map (here prefixing with "a" for example):

Map["a" <> # &, result, {-1}]
Map["a" <> IntegerString@# &, l, {-1}]


Both give:

{"a1",{"a2",{{"a3","a4"},{"a5","a6"}},"a7","a8"}}

• Thank you, this is almost the ideal answer, but please see the follow up question in the comments to the question itself ... and then I accept this one, although all answers are really good. – EGME May 27 at 20:34
• @EGME see update. – ciao May 27 at 20:42
• Excellent the second Map is what I was looking for ... it is hinted at by the answer below yours. Many thanks! – EGME May 27 at 20:44

Update

If I understand your two-step string prefix concatenation correctly then this should work

s1 = Map[ToString, l, {-1}];

prefix = "EGME ";
Map[prefix <> # &, s1, {-1}]

(* {"EGME 1", {"EGME 2", {{"EGME 3", "EGME 4"}, {"EGME 5", "EGME 6"}}, "EGME 7", "EGME 8"}} *)


Map[ToString, l, {-1}]

(* {"1", {"2", {{"3", "4"}, {"5", "6"}}, "7", "8"}} *)

• Thank you, this is really good too. Please see the follow up question in the comments to the question – EGME May 27 at 20:35

If your list consisted of a mixture of integers and non-integers, then it might be better to use Replace:

l = {1, {2, {{3, 4}, {5, 6.1}}, 7, 8}};

Replace[
l,
i_Integer :> "a" <> IntegerString[i],
{-1}
]


{"a1", {"a2", {{"a3", "a4"}, {"a5", 6.1}}, "a7", "a8"}}

• Thank you, this is also very useful ... – EGME May 28 at 8:12