我目前正在调试一个问题,在这个问题中,Python 3一直在变量中转义反斜杠。
Situation
我已经配置了一个Kubernetes秘密,并且我可以看到它作为env变量在我使用env | grep SECRET的基于debian的容器中被称为机密。“秘密”包含一个密码,密码由字母字符和多个反斜杠组成,例如"h\ell\o“。我现在想在我的python代码中使用这个秘密。我想从env变量中读取它,这样我就不必用纯文本在代码中编写它了。
我使用secret=os.getenv("SECRET")引用env变量并初始化包含秘密的变量。使用python交互式shell直接调用机密显示,它包含"h\ell\o“,因为Python会自动转义反斜杠。调用print(secret)返回"h\ell\o“,因为print将双反斜杠解释为转义反斜杠。
我现在不能使用变量秘密插入密码,因为它总是插入包含双反斜杠的密码,这是错误的密码。
问题
是否有方法禁用自动转义,或替换转义反斜杠?我尝试了几种使用codecs.encode() or codecs.decode()的方法。我还试过使用string.replace()
我不能更改密码。
发布于 2022-01-10 09:43:05
您可以使用repr()获得字符串的确切表示形式。
用例示例可能如下所示:
>>> 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'>
>>>https://stackoverflow.com/questions/70650275
复制相似问题