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
  • 104,438
  • 178
  • 489
  • 842

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
  • 17,779
  • 5
  • 18
  • 45
  • 1
    cool. What about without shlex and just doing: `print(ast.literal_eval("'%s'" % x))` ? – David542 Mar 28 '21 at 07:14
  • @David542, That's even cooler. – ThePyGuy Mar 28 '21 at 07:16
  • Simply interpolating between `''` is not good enough for a variety of reasons. `shlex.quote` can make a real mess of things. Try the input `x = r'''\\ \ \" \\" \\\" \'你好'\n\u062a\xff\N{LATIN SMALL LETTER A}"''' + '\\'` if you really want to test out the quoting mechanism properly. I wrote an answer at the duplicate I just linked, which handles this properly. – Karl Knechtel Aug 05 '22 at 01:57
  • @KarlKnechtel, actually I can not agree more; however, the time when I wrote this answer, I was just thinking about the sample provided by OP TBH. – ThePyGuy Aug 05 '22 at 02:37