Amit Yadav
Amit Yadav

Reputation: 59

How to prevent a new line character (\n) of a string from being the part of the string and not doing its job in python?

Looking for help solving an issue. I have stored a public key in .env file, public key is having \n in it and for .env i have used python dcouple but when I am using the environment variable in a function then \n is not doing its job but it is becoming the part of the string.

.env
KEY=-----BEGIN PUBLIC KEY-----\nAp4k567H7J7\nG2rtJH\nLok1FG3\n-----END PUBLIC KEY-----\n

utility.py
var = data(KEY=config('KEY'))
print(config('KEY')) #it is not giving the desired result its printing below result
-----BEGIN PUBLIC KEY-----\nAp4k567H7J7\nG2rtJH\nLok1FG3\n-----END PUBLIC KEY-----\n

but i need this string to be like this when used in utility.py
-----BEGIN PUBLIC KEY-----
Ap4k567H7J7
G2rtJH
Lok1FG3
-----END PUBLIC KEY-----

Upvotes: 2

Views: 2258

Answers (2)

sytech
sytech

Reputation: 40921

.env files and libraries that read them, generally, do not support newlines. It appears your env file contains escaped newlines; a literal \n in place of a newline.

In this case, you must unescape the newline characters in the file.

key_data = config('KEY')
key = key_data.replace('\\n', '\n')

Additional reference: https://stackoverflow.com/a/55459738/5747944

You may also consider a different mechanism for storing and retrieving the public key. For example, you may store the system path to the key file in the environment variable and read it from disk, instead.

So in your .env

PUBLIC_KEY_FILE=/path/to/key.pub

Then in code:

key_file_path = config('PUBLIC_KEY_FILE')
with open(key_file_path) as f:
    key = f.read()

Upvotes: 1

synodexine
synodexine

Reputation: 66

The problem is in the way you get it from the file. I have no idea why, but I think, when you get some string from this file, your library, or python, or something else, replaces '\n' with '\\n' so you will not see the expecting output anyway. The solution that I can suggest is to take your string and do this stuff:

key = config('KEY')
key = key.replace('\\n', '\n')

And so you can print key as you wanted. Maybe it is not perfect, but it's going to work.

Upvotes: 4

Related Questions