【问题标题】:input() and literal unicode parsinginput() 和文字 unicode 解析
【发布时间】: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


【解决方案1】:

如果您可以确定输入不包含引号,则可以通过在两端添加引号将输入转换为字符串文字表示,然后使用ast.literal_eval() 将其计算为字符串。示例 -

import ast
inp = input("Input : ")
res = ast.literal_eval('"{}"'.format(inp))

如果输入可以包含引号,您可以在使用 ast.literal_eval 进行评估之前将双引号替换为 r'\"'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 2015-05-09
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多