Print raw string from variable? (not getting the answers)

后端 未结 11 970
后悔当初
后悔当初 2020-12-04 10:14

I\'m trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like \'

11条回答
  •  抹茶落季
    2020-12-04 11:10

    I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.

    Two ways of solving it:

    1. Get the path you want using native python functions, e.g.:

      test = os.getcwd() # In case the path in question is your current directory
      print(repr(test))
      

      This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.

    2. If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:

      test = 'C:\\Windows\\Users\\alexb\\'
      print(repr(test))
      

提交回复
热议问题