diff --git a/README.md b/README.md index 5f61123..6f2d7d0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1867 TILs and counting..._ +_1868 TILs and counting..._ See some of the other learning resources I work on: @@ -1102,6 +1102,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Dunder Methods](python/dunder-methods.md) - [Easy Key-Value Aggregates With defaultdict](python/easy-key-value-aggregates-with-defaultdict.md) - [Enable Pyright Type Checking In Cursor](python/enable-pyright-type-checking-in-cursor.md) +- [Escape Curly Braces Within Formatted String](python/escape-curly-braces-within-formatted-string.md) - [Experiment With SQLite Queries In Memory](python/experiment-with-sqlite-queries-in-memory.md) - [Force Remaining Arguments To Be Named](python/force-remaining-arguments-to-be-named.md) - [Get Absolute Seconds From `timedelta` Object](python/get-absolute-seconds-from-timedelta-object.md) diff --git a/python/escape-curly-braces-within-formatted-string.md b/python/escape-curly-braces-within-formatted-string.md new file mode 100644 index 0000000..6434b8a --- /dev/null +++ b/python/escape-curly-braces-within-formatted-string.md @@ -0,0 +1,47 @@ +# Escape Curly Braces Within Formatted String + +Python's +[_f-string_](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) +allows you to interpolate values into a string literal like so: + +```python +>>> amount = 25 +>>> print(f"Price: ${amount}") +Price: $25 +``` + +The `{` and `}` are betting special treatment when `f` precedes the string +literal. So, what if the resulting string is supposed to have literal `{` and +`}` characters in it? + +```python +>>> f"JSON opens and closes with curlies: {...}" +'JSON opens and closes with curlies: Ellipsis' +``` + +I need a way of escaping them. The trick is to double them up. + +```python +>>> f"JSON opens and closes with curlies: {{...}}" +'JSON opens and closes with curlies: {...}' +``` + +A more practical example of where this is useful is in formatting an expected +string of JSON in a test: + +```python +info_result = runner.invoke(cli, ["info", "--json"]) +output = textwrap.dedent(f""" +{{ + "config_file": "{config_file}", + "data_dir": "{data_dir}", + "version": "{VMT_VERSION}", + "schema_version": 1 +}} +""").strip() +assert output in info_result.output +``` + +I'm doing some interpolation at various points in the string literal, but the +outer curly braces are meant to be literal, the opening and closing of the JSON +object.