Home > Blockchain >  Stop Python from interpreting escaped hex values in string
Stop Python from interpreting escaped hex values in string

Time:10-19

I'm reading a path value from Postgres DB (column type String).

For example: path | "G:\Shared drives\2 test\2021\08.2021\test.xlsx"

The problem is that some of the nested directories in the path starts with integer (as the above), and Python automatically treats those as Hex characters.

\2 is converted to \x02. \08 (treated as \0) converted to \x008 \2021 (treated as \20) converted to \x821

print(repr('"G:\Shared drives\2 test\2021\08.2021\test.xlsx"'))

> '"G:\\Shared drives\x02 test\x821\x008.2021\test.xlsx"'

How can I stop Python from interpreting these hex values, and treat it as raw string?

Expected result:

'"G:\\Shared drives\\2 test\\2021\\08.2021\test.xlsx"'

CodePudding user response:

\ starts an escape sequence in a Python string literals. To prevent this, you have roughly four options:

  1. Properly escape your string. That is, double up every path separator backslash: '"G:\\Shared drives\\2 test\\2021\\08.2021\test.xlsx"'
  2. Use raw strings to prevent escape sequences from being interpreted: r'G:\Shared drives\2 test\2021\08.2021\test.xls'
  3. Use forward slashes instead of backslashes, which are valid as Windows paths: 'G:/Shared drives/2 test/2021/08.2021/test.xls'
  4. Don’t use string literals in your Python code; instead, read the string from some other source (e.g. user input or a file).

CodePudding user response:

Take the raw string:

print(repr(r"G:\Shared drives\2 test\2021\08.2021\test.xlsx"))

Output:

'G:\\Shared drives\\2 test\\2021\\08.2021\\test.xlsx'
  • Related