I have a list and I'm trying to fill it with bracketed elements. In it's simplest form, my issue is that I want example=([])
to become example=([('a','b'),('c','d')])
.
More explicitly, I'm trying to turn the runnable snippet of code below into a function. But I can't get the list called text
to fill properly. Here is the code working:
# import prompt toolkit
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.styles import Style
# My palette
my_palette = {"my_pink": '#ff1493', "my_blue": '#0000ff',}
# The text.
text = FormattedText([('class:my_pink', 'Hello '),('class:my_blue', 'World')])
# Style sheet
style = Style.from_dict(my_palette)
# Print
print_formatted_text(text, style=style)
This my attempt at creating a function, that at one point turns *args
into list elements:
def col(*args):
"""Should take `col['word', 'colour']` and return the word in that colour."""
text = FormattedText([])
for a in args:
text_template = ("class:" + str(a[1]) + "', '" + str(a[0]))
text_template = text_template.replace("'", "")
text.append(text_template)
print(text) # Shows what is going on in the `text` variable (nothing good).
style = Style.from_dict(my_palette)
print_formatted_text(text, style=style)
The function would be run with something like this:
col(["Hello", 'my_pink'], ["World", 'my_blue'])
The text
variable should look like the first example of text
, but brackets are missing and the commas are in strings so it looks like this:
text = FormattedText([('class:my_pink, Hello ', 'class:my_blue', 'World'])
Rather than like this:
text = FormattedText([('class:my_pink', 'Hello '), ('class:my_blue', 'World')])
I tried further manipulation, using variations of the following:
text = format(', '.join('({})'.format(i) for i in text))
But honestly I cant understand how I making such a pigs ear of a simple problem. I have tried a lot of 'jammy' solutions but none work and I would like a pythonic one.
You can use list comprehension and f-string:
def col(*args):
"""Should take `col['word', 'colour']` and return the word in that colour."""
text = FormattedText([(f"class:{a[1]}", str(a[0])) for a in args])
print(text) # Shows what is going on in the `text` variable (nothing good).
style = Style.from_dict(my_palette)
print_formatted_text(text, style=style)