Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you input escape sequences in Python? [duplicate]

Tags:

python

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
like image 413
Bob Smith Avatar asked Sep 12 '25 04:09

Bob Smith


2 Answers

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?

like image 142
BoarGules Avatar answered Sep 14 '25 19:09

BoarGules


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))
like image 45
busybear Avatar answered Sep 14 '25 19:09

busybear