2

Restatement of question, including code.

numList = {"3 ", "(2)^2 ", "foo", "bar"};
Manipulate[nums = Extract[numList, {{1}, {i}}];
 Grid[{{"Perform the following calculation."}, {"input=" <> 
 StringJoin[nums]}, {"ans=" <> 
 ToString[ToExpression[StringJoin[nums]]]}}], {i, Range[2, 4]}]

Paste code into Mathematica. Replace foo with 2, control-6 (to get a superscript), 2. Replace bar with open paren, 2, close paren, control-6, 2. Execute, and then click on the ButtonBar. When i is 2 or 3, it works fine. If you click on i=4, you get a syntax error.

These should all be legal ways of doing 3 times 2^2.

rhomboidRhipper
  • 856
  • 4
  • 7
  • 1
  • What exactly fails? – Kuba Oct 03 '19 at 06:06
  • Gives the following error: ToExpression::sntx: Invalid syntax in or before " (1!(*SuperscriptBox[()), (2)]) ". ^ – rhomboidRhipper Oct 03 '19 at 14:53
  • So, 1 with a superscript 2 works, but if you include the parentheses, it fails. – rhomboidRhipper Oct 03 '19 at 14:54
  • Can you provide more information on what this is needed for and how the strings are generated? Note that e.g. ToExpression@"\!\(\*SuperscriptBox[\((1)\), \(2\)]\)" does work as intended, the problem is that the lack of tokenization inside the string causes the front-end to generate "invalid" box expressions when using 2D input forms. That is to say, it might be possible to simply ensure the box structures are indeed valid when they are generated, instead of trying to fix them – Lukas Lang Oct 03 '19 at 20:31
  • I'm just typing them in by hand. If I need to learn about box structures to see how they work, I guess I'd better start reading. – rhomboidRhipper Oct 03 '19 at 21:38
  • 1
    Is there are particular reason why you want to input your expressions as strings? – Lukas Lang Oct 04 '19 at 08:01
  • 1
    If you look at FullForm[numList] you'll in the last string that "(2)" is not the base of the superscript. This string does what you wanted: "\!\(\*SuperscriptBox[\((2)\), \(2\)]\)" -- not sure how enter it tho' – Michael E2 Oct 05 '19 at 00:03
  • 1
    Hm. I finally emailed Wolfram support, and they say this is a bug, and they'll work on it. – rhomboidRhipper Oct 23 '19 at 16:14

1 Answers1

1

How about this?

ToExpression@StringReplace[
 StringTrim@ToString@"(1\!\(\*SuperscriptBox[\()\), \(2\)]\)",
 pow_ ~~ "\n" ~~ base__ :> base <> "^" <> pow
]

1

NonDairyNeutrino
  • 7,810
  • 1
  • 14
  • 29
  • Thanks, but I'm trying to, in a non-MMtica-user-friendly way, display some text, and then evaluate it. The above is not legible to anyone save a very few of us. – rhomboidRhipper Oct 03 '19 at 14:52