I previously created a thread about str.dedent()
.
Before writing a PEP for it, I would like to consider adding a prefix of d/D
to string literals (d-string).
This is rough idea about d-string:
- d-string starts with triple quote (
"""
or'''
) followed by newline. The newline is not included in the string.d"spam"
andd'''egg'''
are syntax error.
- d-string ends with indent and triple quote. Only the indent to be removed is allowed before closing triple quote in the line.
- Indents in lines that are same to the last line is stripped.
- d-string can be used with âf/Fâ and `r/Râ prefix.
Example:
text = d"""
Lorem ipsum dolor
sit amet, consectetur
"""
# This is equivalent to above.
text = " Lorem ipsum dolor\n\n sit amet, consectetur\n"
# current syntax
text = """\
Lorem ipsum dolor
sit amet, consectetur
"""
The advantages of d-string
over str.dedent
are as follows:
- It has slightly less visual noise than
.dedent()
. It will be nice to be used with multiline string in function arguments. (sample) - It can be combined with f-strings. The indentation can be statically calculated and removed at compile time before evaluating the f-string.
- The string can start with
d"""
instead of"""\
. The compiler will remove the first newline, which can reduce visual noise.- d-strings might make triple quotes and the first newline mandatory.
- It is possible to specify the amount of indentation to remove on the final line of the string.
- This idea is ported from Swift. See Documentation
On the other hand, d-string would complicate Pythonâs syntax, as opposed to str.dedent()
, which is just one method. There are currently 14 combinations in stringprefix. I donât know how difficult it would be to add d/D
to this.
stringprefix ::= "r" | "u" | "R" | "U" | "f" | "F"
| "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"