Advanced String Literals

This commit is contained in:
a 2020-10-04 18:39:51 +03:00
parent 580b675f1a
commit 02be19096e
2 changed files with 59 additions and 2 deletions

View file

@ -902,8 +902,42 @@ to be evaluated in Python mode using the ``@()`` syntax:
>>> echo @("my home is $HOME") >>> echo @("my home is $HOME")
my home is $HOME my home is $HOME
You can also disable environment variable expansion completely by setting
``$EXPAND_ENV_VARS`` to ``False``. .. note::
You can also disable environment variable expansion completely by setting
``$EXPAND_ENV_VARS`` to ``False``.
Advanced String Literals
========================
For fine control of envvar substitutions, brace substitutions and backslash escapes
there are extended list of literals:
- ``"foo"`` - regular string: backslash escapes.
- ``r"foo"`` - raw string: unmodified.
- ``f"foo"`` - formatted string: brace substitutions, backslash escapes.
- ``fr"foo"`` - raw formatted string: brace substitutions.
- ``p"foo"`` - path string: backslash escapes, envvar substitutions, returns Path.
- ``pr"foo"`` - raw Path string: envvar substitutions, returns Path.
- ``pf"foo"`` - formatted Path string: backslash escapes, brace substitutions, envvar substitutions, returns Path.
To complete understanding let's set environment variable ``$EVAR`` to ``1`` and local variable ``var`` to ``2``
and make a table that shows how literal changes the string in Python and subprocess mode:
.. table::
======================== ========================== ======================= =====================
String literal As python object print(<String literal>) echo <String literal>
======================== ========================== ======================= =====================
``"/$EVAR/\'{var}\'"`` ``"/$EVAR/'{var}'"`` ``/$EVAR/'{var}'`` ``/1/'{var}'``
``f"/$EVAR/\'{var}\'"`` ``"/$EVAR/'2'"`` ``/$EVAR/'2'`` ``/1/'2'``
``r"/$EVAR/\'{var}\'"`` ``"/$EVAR/\\'{var}\\'"`` ``/$EVAR/\'{var}\'`` ``/$EVAR/\'{var}\'``
``fr"/$EVAR/\'{var}\'"`` ``"/$EVAR/\\'2\\'"`` ``/$EVAR/\'2\'`` ``/$EVAR/\'2\'``
``p"/$EVAR/\'{var}\'"`` ``Path("/1/'{var}'")`` ``/1/'{var}'`` ``/1/'{var}'``
``pr"/$EVAR/\'{var}\'"`` ``Path("/1/\\'{var}\\'")`` ``/1/\'{var}\'`` ``/1/\'{var}\'``
``pf"/$EVAR/\'{var}\'"`` ``Path("/1/'2'")`` ``/1/'2'`` ``/1/'2'``
======================== ========================== ======================= =====================
Filename Globbing with ``*`` Filename Globbing with ``*``
=============================== ===============================

23
news/tutorial_literal.rst Normal file
View file

@ -0,0 +1,23 @@
**Added:**
* Added "Advanced String Literals" to the "Tutorial".
**Changed:**
* <news item>
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* <news item>
**Security:**
* <news item>