【发布时间】:2016-01-13 22:42:00
【问题描述】:
使用input() 将反斜杠作为文字反斜杠,因此我无法使用 unicode 解析字符串输入。
我的意思:
将"\uXXXX\uXXXX\uXXXX" 之类的字符串粘贴到input() 调用中将被解释为"\\uXXXX\\uXXXX\\uXXXX",但我希望它读取\u 作为单个字符而不是两个单独的字符。
有谁知道如何或如果可能的话?
编辑:我按上述方式输入并将其转换为 ascii,如下所示..
import unicodedata
def Reveal(unicodeSol):
solution = unicodedata.normalize('NFKD', unicodeSol).encode('ascii', 'ignore')
print(solution)
while(True):
UserInput = input("Paste Now: ")
Reveal(UserInput)
根据我标记的答案,正确的解决方案是:
import unicodedata
import ast
def Reveal(unicodeSol):
solution = unicodedata.normalize('NFKD', unicodeSol).encode('ascii', 'ignore')
print(solution)
while(True):
UserInput = ast.literal_eval('"{}"'.format(input("Paste Now: ")))
Reveal(UserInput)
【问题讨论】:
-
你用什么代码来打印字符串?请显示您的输出或解释器会话。
-
input() 不对转义序列 afaik 进行任何特殊解析,它只是按字面意思返回用户键入的内容。如果(例如)用户输入了格式错误的转义序列,您希望发生什么?这里有办法解决这个问题:stackoverflow.com/questions/4020539/…
-
这些字符串的来源是什么?如果需要
ast.literal_eval()或unicode-escape编码;上游有东西坏了。input()按原样接受并返回 Unicode 字符串。print(ascii(input('Paste Now: ")))是什么?
标签: python python-3.x input unicode unicode-literals