# Change nested list of symbols to nested list of numbers

I have some nested lists of symbols, all of the same format, and I wish to convert them to nested lists of integers, i.e.

{e1,{e1,{e1,e2}}} -> {1,{1,{1,2}}}


Any quick ways to do this?

Note: I will always have nested lists of that form, but their length may vary and the symbols may not always have single digit integers in them, e.g.

{e4,{e200,{e1,{e11,e23}}}} -> {4,{200,{1,{11,23}}}}


Many thanks!

symbols = {e4, {e200, {e1, {e11, e23}}}};
Map[FromDigits@StringDrop[SymbolName[#], 1] &, symbols, {-1}]


{4, {200, {1, {11, 23}}}}

Map[FromDigits @ StringCases[SymbolName[#], NumberString] &, symbols, {-1}]


{4, {200, {1, {11, 23}}}}

Alternative versions, as suggested by Kuba,

Function[, FromDigits@StringDrop[SymbolName[#], 1], Listable]@symbols
Function[, FromDigits@StringCases[SymbolName[#], NumberString], Listable]@symbols


And, inspired by Jack LaVigne's comment, Replace and ReplaceAll:

Replace[symbols, s_Symbol:>   FromDigits[StringDrop[SymbolName[s], 1]],∞ ]
symbols /. Except[List, s_Symbol] :> FromDigits@StringDrop[SymbolName[s], 1]


Finally, per J.M.'s comment, a variation on Coolwater's answer with combination of ToExpression and StringDelete:

 ToExpression @ StringDelete[LetterCharacter]@ToString@symbols

• Here's an alternative for Map: Function[sym, ..., Listable].
– Kuba
Commented Sep 29, 2018 at 16:50
• Thank you @Kuba; great suggestion.
– kglr
Commented Sep 29, 2018 at 16:57
• @kglr Another alternative for Map is to use ReplaceAll. symbols /. e_Symbol /; Not[MatchQ[e, List]] :> FromDigits@StringDrop[SymbolName[e], 1] Commented Sep 29, 2018 at 21:33
• @JackLaVigne fyi ... /. e:Except[List, _Symbol] ...
– Kuba
Commented Sep 29, 2018 at 22:08
• @DanielWilson-Nunn, without FromDigits or ToExpression wrapping we get {"4", {"200", {"1", {"11", "23"}}}} .
– kglr
Commented Nov 10, 2018 at 21:02

Alternatively:

symbols = {e4, {e200, {e1, {e11, e23}}}};
ToExpression[StringReplace[ToString[symbols], "e" -> ""]]


{4, {200, {1, {11, 23}}}}

• ...or, ToExpression[StringDelete[ToString[symbols], "e"]] Commented Sep 29, 2018 at 19:56

Another way using SymbolToSubscript:

symbols = {e4, {e200, {e1, {e11, e23}}}};

ResourceFunction["SymbolToSubscript"][symbols] /. Subscript[a_, b_] :> b

(*{4, {200, {1, {11, 23}}}}*)

symbols = {e4, {e200, {e1, {e11, e23}}}};


Using Replace

Replace[symbols, s_ :>
ToExpression @ StringJoin @ Rest @ Characters @ ToString[s], {-1}]


{4, {200, {1, {11, 23}}}}