0

I ask user for some input using

s = input('enter something: ')

Then I save it to a text file. I want my user to be able to input new lines using '\n'.

For example, if user input "hello\nbye", and I use file.write(s) to save the text, I want my text file to be:

hello
bye

But just typing in '\n' does not seen to work. Specifying a replacement character then using str.replace is not an option for me. I am using Python 3.11 but I can switch to any Python 3 version.

EDIT: I am interacting with the user through socket, and I cannot use sys.stdin.read() due to limitations with the console. I also cannot use the iter based solution as I only want the user to input once. Therefore, How to read multiple lines of raw input? does not resolve my issue.

Billy Cao
  • 335
  • 4
  • 15

1 Answers1

0

Since python's input can't turn \n into newline characters, you may need to do the conversion yourself:

s = input('enter something: ') #e.g "hello\nworld"
s = s.replace('\\n', '\n') # turns literal '\n' text into newline characters
...
file.write(s)

Now, s will have newlines instead of \n and will write and print as expected.

Adid
  • 1,504
  • 3
  • 13
  • I know this but as I said in the question, str.replace is not an option for me. Thank you anyways. – Billy Cao Nov 20 '22 at 12:39
  • I missed that requirement - input doesn't seem to have any built-in ways of interpreting escape codes. – Adid Nov 20 '22 at 12:44