【问题标题】:Print string in a form of Unicode codes以 Unicode 代码的形式打印字符串
【发布时间】:2010-02-05 09:36:03
【问题描述】:

如何在 Python 中将字符串打印为 unicode 代码序列?

输入:"если"(俄语)。

输出:"\u0435\u0441\u043b\u0438"

【问题讨论】:

    标签: python string unicode


    【解决方案1】:

    这应该可行:

    >>> s = u'если'
    >>> print repr(s)
    u'\u0435\u0441\u043b\u0438'
    

    【讨论】:

      【解决方案2】:

      代码:

      txt = u"если"
      print repr(txt)
      

      输出:

      u'\u0435\u0441\u043b\u0438'
      

      【讨论】:

        【解决方案3】:
        a = u"\u0435\u0441\u043b\u0438"
        print "".join("\u{0:04x}".format(ord(c)) for c in a)
        

        【讨论】:

        • 当然,但它也为 ascii 字符提供 unicode,这可能是可取的。但是您应该在该列表理解周围有一个 ''.join() 。 ;)
        • @Lennart:是的,谢谢。从 repr 的返回值中提取字符串有点繁琐(在 Python 3 中会有所改变,因为 u 前缀已经消失)。
        【解决方案4】:

        如果你需要特定的编码,你可以使用:

        txt = u'если'
        print txt.encode('utf8')
        print txt.encode('utf16')
        

        【讨论】:

          猜你喜欢
          • 2015-03-05
          • 1970-01-01
          • 2019-05-01
          • 1970-01-01
          • 2014-08-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-16
          相关资源
          最近更新 更多