如何在Python中将unicode字符串格式化为utf8?

2024-10-01 04:46:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读一个JSON字符串,里面到处都是u'string'样式的字符串。示例:

 [
     {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        }, 
        "year": {
          "value": "1996"
        }
      }, 
      "guid": "#9202a8c04000641f80000000003a0ee6", 
      "type": "\/games\/game", 
      "id": "\/en\/el_grande", 
      "name": "El Grande"
    }, 
    {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        }, 
        "year": {
          "value": "1995"
        }
      }, 
      "guid": "#9202a8c04000641f80000000000495ec", 
      "type": "\/games\/game", 
      "id": "\/en\/settlers_of_catan", 
      "name": "Settlers of Catan"
    }
  ]

如果我指定名称=结果.名称. 然后当我记录将该值传递给Django模板时,它显示为u'Dominion'

如何将其格式化为显示为Dominion?在

++更新++

我认为问题与打印列表或字典中的值有关。例如:

^{pr2}$

显示为:

(u'Dominion',)  // saved response to dictionary, and then printed
Dominion        // when calling the value directly from the response

我需要遍历一个JSON项数组,并且值用unicode显示。为什么?在


Tags: 字符串idjsonforvalueyearenguid
3条回答
>>> # example
>>> s = u"Jägermütze"
>>> s.encode("utf-8")
'J\xc3\xa4germ\xc3\xbctze'
>>> print s.encode("utf-8") # on a utf-8 terminal
Jägermütze

对Django不太了解,但不接受snicode字符串对我来说似乎不太和谐。在

您可以使用str(your string)来执行此操作。在

games["name"] = name,结尾的逗号使其成为1元组。把它取下来。在

相关问题 更多 >