【问题标题】:Python: Why I can print a Unicode character on one line of code, but the same Unicode character causes an error when I try to print it later?Python:为什么我可以在一行代码上打印一个 Unicode 字符,但是当我稍后尝试打印时,相同的 Unicode 字符会导致错误?
【发布时间】:2016-11-30 07:12:21
【问题描述】:

我正在使用 BeautifulSoup4 编写一个 Python 程序,当我获取一个包含风格化引号 u'\u2019' 的 HTML 元素时,我能够打印出 整个 像这样的元素:

代码:

print "Using song: %s" % (song_link)

结果:

Using song: <a href="http://www.songlyrics.com/anna-kendrick/cups-pitch-perfects-when-im-gone-lyrics/" title="Cups (Pitch Perfect’s “When I’m Gone”) Lyrics Anna Kendrick">Cups (Pitch Perfect’s “When I’m Gone”)</a>


但是当我尝试打印出该元素的文本时,它会失败:

代码:

print "Song text: %s" % (song_link.text)

结果:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 30: ordinal not in range(128)


为什么会这样?为什么这一刻有效,下一刻无效?它是可重现的。

【问题讨论】:

    标签: python unicode beautifulsoup ascii


    【解决方案1】:

    第一个案例的输出是一个字节字符串。第二种情况的输出是一个 Unicode 字符串。 Unicode 字符串被隐式编码为终端编码,如果终端编码无法确定,则为ascii,这会导致您的错误。

    不了解您的环境,您需要确定为什么打印 Unicode 字符串默认使用ascii 编码,或者自己使用.encode('utf8') 显式编码字符串。

    【讨论】:

    • 在打印之前在字符串上调用 .encode('utf8') 似乎已经修复了它 - 谢谢!
    猜你喜欢
    • 2011-02-05
    • 2022-01-25
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 2018-06-22
    相关资源
    最近更新 更多