Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"\n" in strings not working

I have this little piece of code for my sort of Operating System:

print("Type your document below.")
print("Press enter to save.")
print("Type \\n for a new line.")
file=input()
print("Enter a file name...")
filename=input()
outFile = open(filename, "w+")
outFile.write(file)
outFile.close()

but when I run this code (which is in a def), say I enter something like this:

foo \n bar

because enters dont work when recieving input from the users, so you have to use \n.

the file turns out as:

foo \n bar

instead of:

foo
bar
like image 1000
Xtreme Avatar asked Jul 15 '16 16:07

Xtreme


1 Answers

Note that if you want to support Python-style strings (with not only \n but also \t, \r, \u1234, etc.), you should use codecs.decode with the unicode_escape handler:

contents = input()
contents = codecs.decode(contents, "unicode_escape")

Note that this will change

foo\nbar\\nbash\u1234

to

foo
bar\nbashሴ

You will also want to handle errors. You can do this either by catching UnicodeDecodeError or by using an error replacement policy:

contents = input()
contents = codecs.decode(contents, "unicode_escape", errors="replace")

Sadly this seems to mess with unicode characters:

codecs.decode("α", "unicode_escape")
#>>> 'α'

The simplest fix I know of is to first escape with raw_unicode_escape:

contents = input()
contents = contents.encode("raw_unicode_escape")
contents = contents.decode("unicode_escape")

This is probably far more complicated than you need, so I suggest not actually doing this.

like image 76
Veedrac Avatar answered Oct 07 '22 10:10

Veedrac