Python 如何接受包含转义字符的字符串
如果用户输入一个包含转义字符的字符串(例如“Example\”或“C:\Users…),我希望完全按原样接受它。换句话说,我试图避免在处理上述输入时抛出的语法错误 我觉得应该很简单,但我找不到答案。有什么帮助吗 编辑:我使用的是Python3不要使用Python 如何接受包含转义字符的字符串,python,string,escaping,Python,String,Escaping,如果用户输入一个包含转义字符的字符串(例如“Example\”或“C:\Users…),我希望完全按原样接受它。换句话说,我试图避免在处理上述输入时抛出的语法错误 我觉得应该很简单,但我找不到答案。有什么帮助吗 编辑:我使用的是Python3不要使用input();在接受字符串输入时使用raw\u input() input()(在Python 2上)尝试将输入字符串解释为Python,raw\u input()根本不尝试解释文本,包括不尝试将\反斜杠解释为转义序列: >>>
input()
;在接受字符串输入时使用raw\u input()
input()
(在Python 2上)尝试将输入字符串解释为Python,raw\u input()
根本不尝试解释文本,包括不尝试将\
反斜杠解释为转义序列:
>>> 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!'
在Python3上,只使用input()
(这是Python2的raw\u input()
重命名);除非同时使用eval()
,否则它不会解释转义码:
>>> 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!'
在接受字符串输入时,不要使用input()
;而是使用raw\u input()
input()
(在Python 2上)尝试将输入字符串解释为Python,raw\u input()
根本不尝试解释文本,包括不尝试将\
反斜杠解释为转义序列:
>>> 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!'
在Python3上,只使用input()
(这是Python2的raw\u input()
重命名);除非同时使用eval()
,否则它不会解释转义码:
>>> 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!'
如果您使用的是python 2.7,请使用raw_input(),它接受带有特殊字符的字符串 示例程序
$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
如果您使用的是python3,请使用input(),它接受带有特殊字符的字符串,因为python3没有raw_input()函数
如果您使用的是python 2.7,请使用raw_input(),它接受带有特殊字符的字符串 示例程序
$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
如果您使用的是python3,请使用input(),它接受带有特殊字符的字符串,因为python3没有raw_input()函数
处理输入时,使用
eval()
函数。将输入作为参数传递到eval()
函数中。
例如:
PYTHON 3
x=input()
x=评估值(x)
或
x=eval(输入())
输出:
处理输入时,使用
eval()
函数。将输入作为参数传递到eval()
函数中。
例如:
PYTHON 3
x=input()
x=评估值(x)
或
x=eval(输入())
输出:
²
当您想使用原始输入
(或Python3.x)时,您很可能正在Python2.x中使用输入
。Python3,经过后期编辑以反映我不明白如何从Python3中的输入()
调用中获得语法错误
。(假设这就是您正在做的——您没有显示任何描述“已处理”含义的代码。)您可以添加import sys
和print(sys.version)吗
到您的程序中,以确保您使用的是您认为自己使用的Python?当您想使用raw\u input
(或Python 3.x)时,您很可能正在Python2.x中使用input
。Python3,后编辑以反映我不明白如何从Python3中的input()
调用中获得语法错误。(假设这就是您正在做的——您没有显示任何描述“已处理”含义的代码。)您可以将import sys
和print(sys.version)
添加到您的程序中,以确保您使用的是您认为的Python吗?对不起,我应该指定。我使用的是Python3@pipsqueaker117:Updated.Python 3input()
与Python2raw\u input()函数相同。对不起,我应该指定。我使用的是Python3@pipsqueaker117:Updated.Python 3input()
与Python 2raw\u input()函数是相同的函数。