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

2
  • Answered here - stackoverflow.com/questions/11664443/… Commented May 3, 2018 at 3: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')). Commented May 3, 2018 at 3:41

2 Answers 2

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!
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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?
For some reason there isn't a nice way to do this: stackoverflow.com/questions/4020539/…
Okay that's a definite improvement. It still can't decode if there is a '\' at the end though
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.