Gimp-Forum.net
Concatenate a layer name with fixed text and variables - Printable Version

+- Gimp-Forum.net (https://www.gimp-forum.net)
+-- Forum: GIMP (https://www.gimp-forum.net/Forum-GIMP)
+--- Forum: Extending the GIMP (https://www.gimp-forum.net/Forum-Extending-the-GIMP)
+---- Forum: Scripting questions (https://www.gimp-forum.net/Forum-Scripting-questions)
+---- Thread: Concatenate a layer name with fixed text and variables (/Thread-Concatenate-a-layer-name-with-fixed-text-and-variables)



Concatenate a layer name with fixed text and variables - tkemmere - 02-11-2023

Hi all,

I'm learning Python as I go along in the Gimp. Can somebody get me going on this one please?

I have a few variables loaded with figures. (blur is for example 10 and contrast 0.15). I would like to set a layer name, so that later I can save the layer with a filename based on the layer name.

But how do I combine fixed text and variables? It must be something like this, but how exactly?

Code:
pdb.gimp_item_set_name(new_layer, "Blur "+{blur}+"contrast "+{contrast})

I would like the layer name to be "Blur 10 contrast 0.15".

I also tried with "&" but that didn't work either. Nor did it without the "{}".

Am I close? Thanks!  Smile


RE: Concatenate a layer name with fixed text and variables - Ofnuts - 02-11-2023

What you want to do is called string formatting. There are several forms in Python v2, and even more forms in Pythin v3. The simplest form uses the percent operator:

Code:
pdb.gimp_item_set_name(new_layer, "Blur %3.1f, contrast %2d" % (blur,contrast))
  • The things after the % in the format string ("Blur %3.1f, contrast %2d") are format specifications:
    • 3.1f means at least 3 characters wide, at least one decimal and expects a floating point value
    • %2d means integer (base 10), at least 2 characters wide (%d would mean: just what is needed), and expects an integer
    • You can also find %s for string (or whatever the __str__ method returns for an object.
  • Format specs are replaced by the values at the same position in the tuple that follows the % operator ((blur,contrast)). If you have only one format value you can skip the tuple.

In Pythonv3 you could use an "f-string":
Code:
pdb.gimp_item_set_name(new_layer,f'Blur: {blur:3.4f}, contrast: {contrast:d}')
but so far in Gimp you have to stick to Python v2.


RE: Concatenate a layer name with fixed text and variables - tkemmere - 02-12-2023

Thank you Offnuts!

More complex than I expected, but...
...I understand why that is so, cause this way offers much versatility
...well explained by you!

I got it going almost immediately!  Big Grin

Code:
...
[
    (PF_SLIDER, "contrast", "Contrast", 0, (0, 0.5, 0.01)),
    (PF_SLIDER, "blur", "Blur", 0, (0, 99, 1)),
]
...

pdb.gimp_item_set_name(new_layer, "Blur %2d, contrast %4.2f" % (blur,contrast))
Thanks again!