简体   繁体   中英

Python is auto-escaping backslashes in variables


I'm currently trying to debug a problem where Python 3 keeps escaping backslashes in a variable.

Situation
I have a Kubernetes Secret configured and I can see it as env variable called SECRET inside my debian-based container using env | grep SECRET env | grep SECRET . The Secret contains a Password that consists of alphabetical characters and multiple single backslashes *eg "h\ell\o" . I now want to use that secret in my python code. I want to read it from an env variable so I don't have to write it in my code in plain text.
I use secret=os.getenv("SECRET") to reference the env variable and initialize a variable containing the secret. Using the python interactive shell calling secret directly shows, that it contains "h\\ell\\o" because Python is automatically escaping the backslashes. Calling print(secret) returns "h\ell\o" as print is interpreting the double backslashes as escaped backslashes.
I now cannot use the variable SECRET to insert the password, since it always inserts it containing double backslashes, which is the wrong password.
Image showing the described situation

Question
Is there a way to disable auto escaping, or to replace the escaped backslashes? I tried several methods using codecs.encode() or codecs.decode() . I also tried using string.replace()
I cannot change the password.

You can use repr() to get the exact representation of your string.

An example for your use-case may look something like this:

>>> secret = "h\\ell\\o"
>>> print(secret)
h\ell\o
>>> print(repr(secret))
'h\\ell\\o'
>>> fixed_secret = repr(secret).replace("'", "") # Remove added ' ' before and after your secret since ' ' only represent the string's quotes
>>> print(fixed_secret)
h\\ell\\o
>>>
>>> # Just to make sure that both, secret and fixed_secret, are of type string
>>> type(secret)
<class 'str'>
>>> type(fixed_secret)
<class 'str'>
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM