4
$\begingroup$

For example, I have a number with style like so: Style[1, Red, 20]

How do I remove its style, so it returns to its inner value 1? Is there a function that can allow me to remove the head "Style"?

$\endgroup$
3
  • 2
    $\begingroup$ Look at First. $\endgroup$
    – Jason B.
    Commented Mar 18, 2020 at 15:10
  • $\begingroup$ Helpful, but further question is if it's a mixed number and styled number.. Say {1,Style[2,Red],3,Style[4,Red]} $\endgroup$
    – liang
    Commented Mar 18, 2020 at 15:15
  • $\begingroup$ Somewhat related: (29817) $\endgroup$
    – Mr.Wizard
    Commented Mar 18, 2020 at 15:59

4 Answers 4

6
$\begingroup$

Without greater context I recommend a simple ReplaceAll operation, to work on all appearances of Style at any level.

{1, Style[2, Red], 3, Style[4, Red]} /. Style[x_, ___] :> x
{1, 2, 3, 4}

If you want to strip Style from only numbers then you could use something like:

/. Style[x_?NumberQ, ___] :> x
$\endgroup$
5
$\begingroup$

This should work (untested):

removeStyle[expr_Style] := removeStyle@First[expr]
removeStyle[expr_] := expr

The best solution would be to avoid storing styled numbers in the first place, if you intend to compute with them. Only style them at the last minute before displaying them, but do not store the styled version if you can avoid it.

$\endgroup$
1
  • 1
    $\begingroup$ +1 for the good advice $\endgroup$
    – liang
    Commented Mar 18, 2020 at 16:22
4
$\begingroup$

Perhaps something like (not extensively tested)?

stripStyle = ToExpression@*StripBoxes@*ToBoxes

which strips general non-semantic elements from an expression

{1, Style[2, Red], 3, Style[4, Red], Framed[6]} // stripStyle
(* {1, 2, 3, 4, 6} *)
$\endgroup$
2
  • 1
    $\begingroup$ Nice method. One caveat: (216544) $\endgroup$
    – Mr.Wizard
    Commented Mar 18, 2020 at 16:42
  • $\begingroup$ Good comment! Thanks. $\endgroup$
    – chuy
    Commented Mar 18, 2020 at 17:29
2
$\begingroup$

You can use the Format | Clear Formatting menu item for this. Highlight the offending symbols, and use the menu item. There should also be a keyboard shortcut, on MacOS it is Shift + Command + Delete.

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