Skip to content Skip to sidebar Skip to footer

How Do You Input Escape Sequences In 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

Solution 1:

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?


Solution 2:

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))

Solution 3:

Hi you can't input \n as it would result in the input closing. Here is what you can try :

  1. use replace to post-process the string
input().replace("\\n", "\n")
  1. use while to input until you get an empty line
inputs = []
current = input()
while current:
    inputs.append(current)
    current = input()
"\n".join(inputs)

Solution 4:

Python can do this natively:

text = r"Hello\nworld!"
text = text.encode().decode( "unicode_escape" )
print( text )

Note that your shell's (shlex) escaping - if any - may differ from Python's own escape protocol, which is used for parsing the strings in user code.


Post a Comment for "How Do You Input Escape Sequences In Python?"