V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Yo_oY
V2EX  ›  问与答

Python中unicode字符串强制转换的问题

  •  
  •   Yo_oY · 2013-02-25 21:05:35 +08:00 · 8793 次点击
    这是一个创建于 4049 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在Python里面使用unicode型的字符是这样:
    >>> a = u'你好'
    >>> a
    >>> u'\u4f60\u597d'
    >>> print a
    >>> 你好

    那我现在有个字符串是str型的,而且内容已经是unicode编码,比如:
    >>> b = '\u4f60\u597d'
    >>> b
    >>> '\\u4f60\\u597d'
    >>> print b
    >>> \u4f60\u597d

    现在要将b转换成unicode的“你好”,也就是a那样,该怎么做?

    谢谢大家!
    7 条回复    1970-01-01 08:00:00 +08:00
    Yo_oY
        1
    Yo_oY  
    OP
       2013-02-25 21:29:54 +08:00
    自己找到了,XD
    Via: http://hi.baidu.com/kanif/item/398612af052770ad29ce9d99

    def ustr2unicode(input):
    end = len(input)
    pos = 0
    output = u""
    while pos < end:
    if pos <= end - 6 and input[pos] == '\\' and input[pos+1] == 'u':
    output += unichr(int(input[pos+2:pos+6], 16))
    pos = pos + 6
    else:
    output += unicode(input[pos])
    pos += 1

    return output
    reorx
        2
    reorx  
       2013-02-25 21:39:28 +08:00   ❤️ 1
    lianghai
        3
    lianghai  
       2013-02-25 23:18:50 +08:00
    给一楼跪……
    reorx
        4
    reorx  
       2013-02-25 23:52:54 +08:00
    @Yo_oY 忽然发现。。我们好像在一个 clan 里 :D
    Yo_oY
        5
    Yo_oY  
    OP
       2013-02-26 00:49:33 +08:00
    @reorx 原来可以这么简单。是在一个Clan啊,你的名字印象蛮深的,还想问你是不是那个虾米播放器的作者来着。
    swulling
        6
    swulling  
       2013-02-26 01:29:02 +08:00
    lz一般是要解析js中的unicode吧。。。
    Yo_oY
        7
    Yo_oY  
    OP
       2013-02-26 07:20:07 +08:00
    @swulling 完全正确。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3135 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:29 · PVG 22:29 · LAX 07:29 · JFK 10:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.