3

I want to create a XLSX file in python. For this, I use xlsxwriter.

In my XLSX I want to highlight some part of text with the write_rich_string method.

But, my string is not a fixed value. The part I want to highlight can be randomly placed into it. Or I can have multiples part of the text to highlight.

So, can I create a "list of parameters" for the call of write_rich_string? And what is the method to made this?

Example:

mystring = "I want this in [tag_1]yellow[/tag_1] and this in [tag_2]green[/tag_2]."

worksheet.write_rich_string('A1',
                        'I want this in',
                        yellow, 'yellow',
                        ' and this is ',
                        green, 'green')

worksheet.write_rich_string('A1', my_list_of_parm)
gatchan
  • 75
  • 2
  • 7
  • For some background, here is the [documentation for write_rich_string()](https://xlsxwriter.readthedocs.org/en/latest/worksheet.html#worksheet-write-rich-string) which explains how to format a multi-format "rich" string. – jmcnamara Sep 12 '13 at 09:28

1 Answers1

8

If I understand what you're asking… you've got a list like this:

my_list_of_parm = ['I want this in',
                   yellow, 'yellow',
                   ' and this is ',
                   green, 'green']

And you want to pass that to write_rich_string as a bunch of separate arguments (along with one normal argument).

The way to do that is explained in the tutorial under Unpacking Argument Lists: Just put * before my_list_of_parm, and it will be unpacked into separate arguments:

worksheet.write_rich_string('A1', *my_list_of_parm)

In general, if you want to convert a list (or other iterable) into separate values or vice-versa, * is the answer:

>>> def func(a, b, *args):
...     print(args)
>>> func(1, 2, 3, 4, 5)
[3, 4, 5]
>>> a, b, *rest = [1, 2, 3, 4, 5]
>>> rest
[3, 4, 5]
>>> func(1, *rest)
[4, 5]

But for the exact rules on what you can and can't do, you'll need to read the docs.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • hey - when you state "You'll have to read the docs" do you have any pointers about where I would go about searching for this info.... even this page came up as a hail mary click on a google search. – lb_so Mar 17 '21 at 07:35