0

For example, if I did this:

test=input("Text: ")
print(test)

And then set test ashello\nhow are you?, and then call test(), I want it to appear as this:

hello
how are you?

and not

hello\nhow are you?

Is this possible? -darth

Darth
  • 63
  • 11

1 Answers1

5

The sequence \n (so a backslash and a letter n) is an escape sequence. Python string literals support such sequences. Many programming languages support such sequences in string literals too, and so do JSON strings. But that doesn't make such sequences universal.

input() just takes the input the user gave, and returns that input. Nothing more, nothing less, there are no special meanings attached to this, and this is by design. So if you want to give meaning to a series of characters that is different from their normal meaning, then you have to code this yourself.

You could just use str.replace(); if all you want is \n to be a newline, then that's the easiest:

test = input("Text: ")
test = test.replace('\\n', '\n')

Because you have to define string literals to tell str.replace() what to do, you now do have support for escape sequences, and have to tell Python to not make a newline character, but a literal \ followed by a n character, to replace that sequence with an actual newline character.

If you want to support all escape sequences that Python string literals support, then can use the unicode_escape codec, via the codecs.decode() function:

import codecs

test = input("Text: ")
test = codecs.decode(test, 'unicode_escape')

This then interprets all possible escape sequences that the Python string literal syntax supports, including \n, \t, \b, \uhhhh, etc.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343