How to prevent escape characters from changing the output of a randomly generated Python string?

1.1k Views Asked by At

This code outputs a string of randomly generated characters. For example: V86Ijgh(!y7l0+x

import string
import random

password = ''.join([random.choice(string.printable) for i in range(15)])

print(password)

In the case that an escape character like \n appears

V86Ijg\n!y7l0+x

and creates the output:

V86Ijg 
!y7l0+x

because it initialized a new line rather than printing out:

V86Ij\n(!y7l0+x

like before.

What's the best way at avoiding the intended output of an escape character such as creating a new line, tab, etc, from being interpreted? I have no choice over the input because it is randomized. I want to know how to output the string in its raw form without removing characters from the original string. I want the password to be displayed as it was generated.

2

There are 2 best solutions below

0
On BEST ANSWER

You should encode your string with escape characters if you want it to keep the special characters escaped, i.e.:

print(password.encode("unicode_escape").decode("utf-8")) 
# on Python 2.x: print(password.encode("string_escape"))

Using repr() will add single quotes around your string.

2
On

You could make your own set of characters to select frome by taking out all whitespace characters from string.printable, using set operators:

chars = ''.join(set(string.printable) - set(string.whitespace))

password = random.choice(chars)

key_length = 1
while(key_length < 15):
        password += random.choice(chars)
        key_length = key_length + 1

print(password)

Note that this whole loop can be replaced by the list comprehension:

password = ''.join([random.choice(chars) for _ in range(15)])

Edit If you want to keep the escape and whitespace characters, but just want to print the password to your console, use the repr() function:

print(repr(password))