Search code examples
pythonpython-3.xrandomline-breakspassword-generator

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


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.


Solution

  • 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.