46
$\begingroup$

Does anyone know whether it is possible to combine\join two styled strings?

That is, while the following code works fine:

omega = "text";
omega<>omega

when I try to join my omegas into one string but having different colors like this

Style[omega,Lighter[Blue,.1]]<>Style[omega,Darker[LightBlue,.1]]

mma returns this error:

StringJoin::string: String expected at position 1

It's clear to me that the objects I'm trying to join have head Style not String, but may be there is a way to produce a string that has its parts painted in different colors?

$\endgroup$
39
$\begingroup$

Use Row to join them:

Omega = "text";
joined = Row[{Style[Omega, Lighter[Blue, .1]], Style[Omega, Darker[LightBlue, .1]]}];
Print[joined]
$\endgroup$
  • $\begingroup$ Though this is a quick fix for most of the cases, whenever the result is expected to be a String, I prefer WReach's solution. Not to mention that Row breaks lines differently than how the FE prints strings. $\endgroup$ – István Zachar May 13 at 18:07
  • $\begingroup$ Hi István, I agree. Since I read WReach's solution I have found it very useful. $\endgroup$ – Chris Degnen May 13 at 18:32
37
$\begingroup$

Given two styled items:

omega = "text"

items = { Style[omega,Lighter[Blue,.1]], Style[omega,Darker[LightBlue,.1]] }

We can produce a single string with both stylings if we convert each item into a StandardForm string prior to joining them:

Apply[StringJoin, ToString[#, StandardForm] & /@ items]

The following screenshot shows the results:

styled concatenation session

$\endgroup$
  • 5
    $\begingroup$ Nice. Also Row@items ~ToString~ StandardForm though the format is not as clean. $\endgroup$ – Mr.Wizard Sep 23 '12 at 22:11
12
$\begingroup$

If you evaluate or print the following string you get what you want:

"\!\(\*StyleBox[\"text\",FontColor->RGBColor[1, 0, 0]]\) \!\(\*StyleBox[\"text\",FontColor->RGBColor[0, 0, 1]]\)"

Mathematica graphics

This is a single string and it contains color information for different substrings.

Do[Print@"\!\(\*StyleBox[\"text\",FontColor->RGBColor[1, 0, 0]]\) \!\(\*StyleBox[\"text\",FontColor->RGBColor[0, 0, 1]]\)", {5}]

Mathematica graphics

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.