1
$\begingroup$

How can I colorize letters in the given string?

For instance:

string = "jaonvtaqhsy"

How to colorize 3 letters in the middle of string (e,g, "vta")?

I tried:

Split the given string in the three parts

a=StringTake[string, {1, 4}]
b=StringTake[string, {5, 7}]
c=StringTake[string, {8, 11}]

and then colorize each string

aa = Style[a, Blue, Bold]
bb = Style[b, Red, Bold]
cc = Style[c, Blue, Bold]

then join them back together

StringJoin[aa,bb,cc]

or

aa <> bb <> cc

but there is an error message

enter image description here

$\endgroup$
9
  • 1
    $\begingroup$ Try Row@{aa,bb,cc}. Also, your string either needs to be 11 characters long, or c should only take {8,10} This will work for some applications, but may not be flexible depending on what you want to do. $\endgroup$
    – N.J.Evans
    Commented Feb 6, 2017 at 16:09
  • 1
    $\begingroup$ Also, test the form of aa and bb with Head or TreeForm and you will see they are not Strings after you apply the Style function eg, Head@aa $\endgroup$
    – PlaysDice
    Commented Feb 6, 2017 at 16:13
  • $\begingroup$ @N.J.Evans thanks. there is my mistake (10 instead of 11) $\endgroup$
    – vito
    Commented Feb 6, 2017 at 16:14
  • $\begingroup$ closely related: How to change the color of specified digits in a number? $\endgroup$
    – Kuba
    Commented Feb 6, 2017 at 16:26
  • 2
    $\begingroup$ maybe a duplicate: Highlighting or coloring certain words / substrings appearing in a larger string $\endgroup$
    – Kuba
    Commented Feb 6, 2017 at 16:27

2 Answers 2

1
$\begingroup$
highlight[mystring_String, where_List] :=

 Row@{StringTake[mystring, {1, where[[1]] - 1}], 
      Style[StringTake[mystring, where], Red], 
      StringTake[mystring, {where[[2]] + 1, StringLength[mystring]}]}

highlight["abcdefghijkl", {3, 5}]

If you want to highlight a single character,

highlight["abcdefghijkl", {3, 3}]
$\endgroup$
1
$\begingroup$
string = "jaonvtaqhsy"; 
a = StringTake[string, {1, 4}];
b = StringTake[string, {5, 7}];
c = StringTake[string, {8, 11}];
aa = Style[a, Blue, Bold]; 
bb = Style[b, Red, Bold]; 
cc = Style[c, Blue, Bold]; 
ToString[#1, FormatType -> StandardForm] & @ Row[{aa, bb, cc}]

produces a colored string.

$\endgroup$

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