14.5. TOML Strings

14.5.1. SetUp

>>> import tomllib

14.5.2. String

  • TOML's string is Python's str

  • Despite TOML's string being a Unicode string, it is not possible to include a literal newline (\n) in a TOML string.

  • \b - backspace (U+0008)

  • \t - tab (U+0009)

  • \n - linefeed (U+000A)

  • \f - form feed (U+000C)

  • \r - carriage return (U+000D)

  • \e - escape (U+001B)

  • \" - quote (U+0022)

  • \\ - backslash (U+005C)

  • \xHH - unicode (U+00HH)

  • \uHHHH - unicode (U+HHHH)

  • \UHHHHHHHH - unicode (U+HHHHHHHH)

value = "Hello"
value = "Cześć"
value = "Cze\u015B\u0107"
value = "It's Monty Python."
value = "He said: \"It's Monty Python\"."
>>> DATA = 'value = "Cześć"'
>>> tomllib.loads(DATA)
{'value': 'Cześć'}
>>> DATA = 'value = "Hello\nWorld"'
>>> tomllib.loads(DATA)
Traceback (most recent call last):
tomllib.TOMLDecodeError: Illegal character '\n' (at line 1, column 15)

14.5.3. Multiline String

  • TOML's multiline string is Python's str

value = """First line
Second line
Third line"""
>>> DATA = '''
... value = """First line
... Second line
... Third line"""
... '''
>>>
>>> tomllib.loads(DATA)
{'value': 'First line\nSecond line\nThird line'}
value = """\
The quick brown \
fox jumps over \
the lazy dog.\
"""
>>> DATA = '''
... value = """\
... The quick brown \
... fox jumps over \
... the lazy dog.\
... """
... '''
>>>
>>> tomllib.loads(DATA)
{'value': 'The quick brown fox jumps over the lazy dog.'}

14.5.4. Literal String

  • TOML's literal string is Python's str

  • Similar to Python's raw strings: r"..." or r'...'

path1 = 'C:\Users\myuser'
path2 = '\\User\admin$\system32'
quoted = 'Alice "Al" Apricot'
regex = '<\i\c*\s*>'
>>> DATA = r"""
... path1 = 'C:\Users\myuser'
... path2 = '\\User\admin$\system32'
... quoted = 'Alice "Al" Apricot'
... regex = '<\i\c*\s*>'
... """
>>>
>>> tomllib.loads(DATA)
{'path1': 'C:\\Users\\myuser', 'path2': '\\\\User\\admin$\\system32', 'quoted': 'Alice "Al" Apricot', 'regex': '<\\i\\c*\\s*>'}

14.5.5. Multiline Literal String

re = '''I [dw]on't need \d{2} apples'''

lines = '''
The first newline is
trimmed in raw strings.
All other whitespace
is preserved.
'''
>>> DATA = r"""
... re = '''I [dw]on't need \d{2} apples'''
...
... lines = '''
... The first newline is
... trimmed in raw strings.
... All other whitespace
... is preserved.
... '''
... """
>>>
>>> tomllib.loads(DATA)
{'re': "I [dw]on't need \\d{2} apples",
 'lines': 'The first newline is\ntrimmed in raw strings.\nAll other whitespace\nis preserved.\n'}