我正在尝试使用比较字符串对象的列表理解,但其中一个字符串是 utf-8,它是 json.loads 的副产品。设想:
us = u'MyString' # is the utf-8 string
我的问题的第一部分是,为什么这会返回 False?:
us.encode('utf-8') == "MyString" ## False
第二部分 - 我如何在列表理解中进行比较?
myComp = [utfString for utfString in jsonLoadsObj
if utfString.encode('utf-8') == "MyString"] #wrapped to read on S.O.
编辑:我正在使用 Google App Engine,它使用 Python 2.7
这是问题的更完整示例:
#json coming from remote server:
#response object looks like: {"number1":"first", "number2":"second"}
data = json.loads(response)
k = data.keys()
I need something like:
myList = [item for item in k if item=="number1"]
#### I thought this would work:
myList = [item for item in k if item.encode('utf-8')=="number1"]