1

I have a user that can enter in text that a program will print after parsing. That is, the user can enter in something like:

"Print me\nAnd on a newline now"

And it should print as:

Print me
And on a newline now

The string I have now looks like OK\n when I print it and OK\\n when I do repr() on it. I'm having some difficulty converting this to properly print the newline. The only thing that seems to work now is to manually go through each possible entry and do something like:

val = val.replace('\\n', '\n'))
# or, what if they wanted a beep?
# similar to print('\a')

Is there a better way to do this?

David542
  • 101,766
  • 154
  • 423
  • 727

1 Answers1

3

You can use ast and shlex to get the job done.

>>import ast
>>import shlex
>>x = input('Enter the string:')
Enter the string:>? "Print me\nAnd on a newline now"
>>x
'"Print me\\nAnd on a newline now"'

Output:

print(ast.literal_eval(shlex.quote(x)))
"Print me
And on a newline now"

UPDATE: As pointed by @David542, you can even avoid using shlex if you don't want to

>>print(ast.literal_eval("'%s'" % x))
"Print me
 And on a newline now"
ThePyGuy
  • 13,387
  • 4
  • 15
  • 42