开发者

How to format unicode strings to utf-8 in Python?

I'm reading in a JSON string which is littered with u'string' style strings. Example:

 [
     {
      "!\/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"
    }
  ]

If I assign name = result.name. Then when I log of pass that value to a Django template, it displays as u'Dominion'

How do I format it to display as Dominion?

++ UPDATE ++

I think the problem has to do with printing values from a list or dictionary. For example:

result = freebase.mqlread(query)

games = {}
count = 0
r = result[0]
name = r.name
games["name"] = name,
self开发者_如何学Python.response.out.write(games["name"])
self.response.out.write(name)

This displays as:

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

I need to iterate through an array of JSON items and the values are being shown with the unicode. Why?


The comma at the end of games["name"] = name, makes it a 1-tuple. Remove it.


>>> # 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

Don't know much about Django, but not accepting snicode strings seems unpythonic to me.


You can use str(your string) to do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜