How to print f-string (with `=`) path with only a single slash

205 Views Asked by At

Once a while, it was attempted to print the f-string (with =) path without double slashes. Some might have implemented this already.

EDIT:

print(f'{p}') does print single slash, but since I am used to p= format, it is expected to achieve this as well. Backgrounds are that: when you encounter IO errors and stdout path and then copy the given path to explorer. But there are several manual steps to get rid of the double slashes.

>>> p='C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python39_86'
>>> print(p)
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_86
>>> print(f'{p=}')
p='C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python39_86'
>>> print(repr(f'{p=}'))
"p='C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\Shared\\\\Python39_86'"

Add: Following answers, but it is found that the following is not working

>>>print(FileNotFoundError(errno.ENOENT,os.strerror(errno.ENOENT),f'{p=!s}'))
[Errno 2] No such file or directory: 'p=C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python39_86'
1

There are 1 best solutions below

3
Ture Pålsson On

When you use the = syntax in an f-string, you get the repr of the value by default. To get some other conversion, you have to request it explicitly.

p = 'C:\\foo'
print(f'{p=!s}') # Prints p=C:\foo