pythondeprecation-warningf-stringpython-3.10rawstring

How to use escape characters in python fstrings deprecated, without converting to raw string


When running python3.10 -B -Wall testcode.py

I get the following deprecation warnings in my code which I would like to fix

DeprecationWarning: invalid escape sequence '\:'
DeprecationWarning: invalid escape sequence '\:'
DeprecationWarning: invalid escape sequence '\s'

Full code is

import re

vid = r'[0-9a-fA-F]{4}'
pid = r'[0-9a-fA-F]{4}'
device = r'[\S]{8}'

pattern = f'USB VID\:PID\=({vid})\:({pid})\s\SER\=({device})'

with open("datafile.txt", 'r') as ffile:
    r = re.compile(pattern)
    for line in ffile.readlines():
        if r.search(line):
            print(line)

and data text file is

Port:/dev/ttyACM2 Type: A-Blah Desc: USB VID:PID=1234:1951 SER=0A0101294880
Port:/dev/ttyACM0 Type: J-Blah Desc: USB VID:PID=asdasdas:1651 SER=01B01G294880
Port:/dev/ttyACM8 Type: B-Blah Desc: USB VID:PID=1234:F503 SER=8D5VB1294FC1
Port:/dev/ttyACM7 Type: X-Blah Desc: USB VID:PID=53saas86:1251 SER=0010C1294646

desired (and actual) output

Port:/dev/ttyACM2 Type: A-Blah Desc: USB VID:PID=1234:1951 SER=0A0101294880
Port:/dev/ttyACM8 Type: B-Blah Desc: USB VID:PID=1234:F503 SER=8D5VB1294FC1

I know that if I convert the pattern into raw r'...' the warnings go away, but I would like to have the ability to use fstrings without the warnings? Is there any way around it? or should I just use other alternatives to fstring?


Solution

  • You escape \ in an f-string like you would in a normal string: with another backslash.

    pattern = f'USB VID\\:PID\\=({vid})\\:({pid})\\s\\SER\\=({device})'
    

    An IDE like Pycharm will do syntax highlighting for it:

    Pycharm Syntax highlighting

    A raw string only will let the warnings go away, but it will break your program, because the variables like {pid} will become part of the string literally. Note how the syntax highlighting changes for an r-string:

    Pycharm for r-string

    You can however, combine an r-string and an f-string into an rf-string

    pattern = rf'USB VID\:PID\=({vid})\:({pid})\s\SER\=({device})'
    

    Syntax highlighting will show that it works and will not show the squiggly lines for the deprecation warning.

    Pycharm for rf-string