Cleaning escapes on a user-entered string
Question:
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 menAnd on a newline now"
And it should print as:
Print me
And on a newline now
The string I have now looks like OKn
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?
Answers:
You can use ast
and shlex
to get the job done.
>>import ast
>>import shlex
>>x = input('Enter the string:')
Enter the string:>? "Print menAnd 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"
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 menAnd on a newline now"
And it should print as:
Print me
And on a newline now
The string I have now looks like OKn
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?
You can use ast
and shlex
to get the job done.
>>import ast
>>import shlex
>>x = input('Enter the string:')
Enter the string:>? "Print menAnd 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"