Use A Python Format String In A Variable
There are several ways to updates string variables with other variables. The two ways I use the most are .format() and Template Strings.
(Note that this is for dealing with strings in variables. If I'm outputting a string directly I use f-strings which are detailed in the notes further below)
I use the .format() option when there's not a lot of text (e.g. just one line) and the Template Strings when there's several lines (in which case I'm likely reading it in from a file.)
Using .format()
This is the basic setup. A string is stored in the initial_string variable with {} acting as a placeholder for where the replacement value will be inserted.
The next line use calls .format() with the single value we want to use to replace the {} placeholder.
printing it on the next line show our final `hello, world` output.
=
=
hello, world
You can use multiple {} placeholders as well. For example:
=
=
the quick brown fox
Template Strings
I use template strings for longer texts. They use "named placeholders" that start with a $ (e.g. `$color`, `$fruit`, and $drink in this example)
Those values get filled in with their corresponding named arguments (e.g. `color='blue'`) when the template is filled out with `.substitute()`
For example:
=
=
Glue the sheet to the dark blue background.
The juice of lemons makes fine punch.
A pot of tea helps to pass the evening.
#+NOTES
This is what I use if I need to use a variable to hold the string that needs substitutions and replacements. Generally, I use that when I need to pass the string into a function, like:
=
return
=
=
The random number is: 2
If I don't need to put the template for the string in a variable to pass it around I'll use an f-string directly. For example:
=
=
the quick brown fox