【问题标题】:Python read string with 'í' and print itPython用'í'读取字符串并打印它
【发布时间】:2017-05-22 03:45:57
【问题描述】:

我正在使用 python 3.5 读取一个 json 文件。在这个文件中,它有像“í”这样的字符。我想以这种格式打印它。如何让下面的代码正确打印字符?

t = 'í'
print(t)

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print(t)
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 0: ordinal not in range(128)

【问题讨论】:

标签: python unicode iso-8859-1


【解决方案1】:

尝试将# -*- coding: iso-8859-15 -*- 添加为源文件的第一行或第二行。

【讨论】:

    【解决方案2】:

    试试这个 -

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    t = 'í'
    print(t.encode("ascii" , "ignore"))
    

    【讨论】:

      【解决方案3】:

      使用 unicode 格式。

      t = u'i'
      print(t)
      

      您必须在字符“i”之前添加u,以便python 将其理解为unicode。

      【讨论】:

      • 在您输入文字的情况下,这是真的。 OP 的用例是如何从文件中读取字符串?
      • 我们可以在导入json文件的时候指定编码
      • python 2 还是 3??
      • @bigbounty 3.6.1
      • @aryamccarthy 使用以下命令打开 json 文件:with open('ep_meps_current.json', 'r', encoding='utf-8') as fp: meps = json.load(fp)
      【解决方案4】:

      试试这个:

      print(t.decode("utf-8"))
      

      【讨论】:

        猜你喜欢
        • 2019-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-05
        • 2020-02-28
        • 1970-01-01
        • 2012-06-21
        相关资源
        最近更新 更多