Say you make the following program
a=input("Input: ")
print(a)
and try to input the newline character, \n
:
Input: a\nb
a\nb
The input has not been treated as the \n
character but rather as two separate characters, \\
and n
. How do you get an input with an escape sequence to be treated as an escape sequence? The result for the sample above should be
Input: a\nb
a
b
The input
statement takes the input that the user typed literally. The \
-escaping convention is something that happens in Python string literals: it is not a universal convention that applies to data stored in variables. If it were, then you could never store in a string variable the two characters \
followed by n
because they would be interpreted as ASCII 13.
You can do what you want this way:
import ast
import shlex
a=input("Input: ")
print(ast.literal_eval(shlex.quote(a)))
If in response to the Input:
prompt you type one\ntwo
, then this code will print
one
two
This works by turning the contents of a
which is one\ntwo
back into a quoted string that looks like "one\ntwo"
and then evaluating it as if it were a string literal. That brings the \
-escaping convention back into play.
But it is very roundabout. Are you sure you want users of your program feeding it control characters?
You can replace \\n
with \n
to get the result you want:
a = a.replace('\\n', '\n')
input
won't read \
as an escape character.
If you are just interested in printing the input, you can use something like this, which will handle other escape characters. It's not an ideal solution in my opinion and also suffers from breaking with '
.
eval('print("{}")'.format(a))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With