Search code examples
python-3.xunicodef-string

Using \u in python f-string


Is there way to include a \u in an f-string, postponing the evaluation of the escape sequence after the formatting?

A practical example. Let's say I have (python3)

i="0222"
print(f'\u{i}')

This is invalid and returns

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

Is there a way to defer the evaluation of the escape sequence \u after the replacement of {i} in the string?


Solution

  • Is there way to include a \u in an f-string, postponing the evaluation of the escape sequence after the formatting?

    No. Escapes sequences are executed during string parsing.

    Just use the chr builtin, it takes a codepoint (as an integer) and returns the corresponding string.

    If for some fool reason you really absolutely want to use f-strings, then you need to create the escapes themselves in the string object:

    >>> i = 0x0222
    >>> s = f'\\u{i:04x}'
    

    then apply the "unicode_escape" codec, which decodes the escapes at runtime

    >>> codecs.decode(s, encoding='unicode_escape')
    'Ȣ'