0
     with open('practice.txt','w') as x:
          text = input('enter text')
          x.write(text)

enter text .. hello\n world

output .. hello\n world

it takes it as a string not as a newline character why is my input string when passed to a write() not validating my'\n' character

Does it have something to do with me passing input() to write()

SaTown
  • 25
  • 1
  • 3
  • Answered here - https://stackoverflow.com/questions/11664443/how-do-i-read-multiple-lines-of-raw-input-in-python – Odin May 03 '18 at 03:37
  • `\n` is only used to *represent* a newline. Those two characters don't have any special meaning here because `input()` doesn't parse escape sequences. You'll have to figure out a way to do that yourself (e.g. `text = text.replace('\\n', '\n')`). – Blender May 03 '18 at 03:41

2 Answers2

1

input() returns a raw string so all newlines are automatically escaped. You can convert this back into a literal string with literal_eval() from ast.

from ast import literal_eval
with open('practice.txt','w') as x:
      text = input('enter text')
      x.write(literal_eval("'" + text + "'"))

For example:

from ast import literal_eval
a = input()
>>>"\tHello!"
print(a)
>>>\tHello!
print(literal_eval("'" + a + "'"))
>>>    Hello!
Primusa
  • 13,136
  • 3
  • 33
  • 53
  • This will break if you use a single quote anywhere in the text, though. You could use triple quotes (`"'''" + a + "'''"`), but that also breaks for some inputs. – Blender May 03 '18 at 03:44
  • You're right. I can't think of a way to convert it without breaking for at least one type of character. Is there actually no perfect way to convert from raw to literal? – Primusa May 03 '18 at 04:06
  • For some reason there isn't a nice way to do this: https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python – Blender May 03 '18 at 04:20
  • Okay that's a definite improvement. It still can't decode if there is a '\' at the end though – Primusa May 03 '18 at 04:22
0

Another solution would be to use a multiline input from the user, so that you wouldn't need to type the control character.

See here: How to get multiline input from user

Jordan Mann
  • 402
  • 6
  • 16