首页 > 解决方案 > 如何在 Python 2.7 中使用 raw_input 捕获 EOFError 的值?

问题描述

原始数据:

k = {u'description': u'First Contentful Paint marks the time at which the first text or image is painted. [Learn more].', u'title': u'First Contentful Paint', u'score': 1.0, u'scoreDisplayMode': u'numeric', u'displayValue': u'0.5\xa0s', u'id': u'first-contentful-paint'}

片段:

data = k["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"]

try:
    val = raw_input(data.encode("utf-8"))
except EOFError:
    print("skipped")

print "output: " + val

在上面的代码片段中,我如何将结果存储在val; EOFError在线时跳过该步骤val = raw_input(data.encode("utf-8"))

这是我得到的实际输出,我无法将值存储x.x s在变量中

0.5 sskipped

output: 

预期的:

output: 0.5s

蟒蛇版本:2.7

标签: pythonpython-2.7

解决方案


一种解码方法'0.5\xa0s' 是使用unicode内置函数将其转换为 unicode 并告诉它忽略非utf-8字符,并将其转换为字符串

>>> a = '0.5\xa0s'
>>> str(unicode(a, errors='ignore'))
'0.5s'

推荐阅读