Reputation: 2366
If the user inputs a string containing an escape character (e.g. "Example\" or "C:\Users...), I want to accept it exactly as is. In other words, I'm trying to circumvent the Syntax error thrown when input like the above is processed.
I feel like it should be simple, but the answer eludes me. Any help?
EDIT: I'm on python 3
Upvotes: 0
Views: 16040
Reputation: 161
You can use built-in repr() function to returns the string enclosed in single quotes, which will make it possible to use a string contains escape characters as parameter to a function.
for example:
total_path = "D:\to R\wc"
if '.webp' in total_path:
print(f"Found Webp! {repr(total_path)}")
webp_to_png(repr(total_path))
Upvotes: 0
Reputation: 1
When processing the input, use the eval()
function. Pass the input into the eval()
function as an arguement.
For example:
PYTHON 3
x=input()
x=eval(x)
Or
x = eval ( input() )
input the following value:
\N{superscript two}
print ( x )
output:
²
Upvotes: 0
Reputation: 72
if you are using python 2.7 use raw_input() which accepts the string with special chars.
Sample program
$vi demo.py
str1=raw_input("Enter the file with full path : ")
print "Given Path is : ",str
save and quit from vi editor
Output
$python demo.py
Enter the path :/home/ubuntu/deveops
Given path is : /home/ubuntu/deveops
$ python demo.py
Enter the path :\home\ubuntu\deveops
Given path is : \home\ubuntu\deveops
if you are using python3 use input() which accepts the string with special chars because python3 doesnot have raw_input() function
$vi demo1.py
str1=input("Enter the file with full path : ")
print ("Given Path is : ",str1)
save and quit from vi editor
Output
$python demo1.py
Enter the path :/home/ubuntu/deveops
Given path is : /home/ubuntu/deveops
$ python demo1.py
Enter the path :\home\ubuntu\deveops
Given path is : \home\ubuntu\deveops
Upvotes: 0
Reputation: 1125408
Don't use input()
; use raw_input()
instead when accepting string input.
input()
(on Python 2) tries to interpret the input string as Python, raw_input()
does not try to interpret the text at all, including not trying to interpret \
backslashes as escape sequences:
>>> raw_input('Please show me how this works: ')
Please show me how this works: This is \n how it works!
'This is \\n how it works!'
On Python 3, use just input()
(which is Python 2's raw_input()
renamed); unless you also use eval()
it will not interpret escape codes:
>>> input('Please show me how this works: ')
Please show me how this works: This is \n how it works!
'This is \\n how it works!'
Upvotes: 7