Python设置一个变量,字符串变成unicode

2024-05-08 13:20:19 发布

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

我尝试遍历一些json并将键添加到db中。我有一个返回字符串的函数。当我将该字符串分配给变量时,该变量将打印一个unicode字符串。为什么?在

json_obj = json.loads(data)
for resource in json_obj:

    # returns a string
    san_resource = self.sanitize_resource(resource)

    fresource = FertilityResource.objects.get_or_create(
        title = san_resource['Resource Name'],
    )

    print(fresource[0].title, san_resource['Resource Name'])

def sanitize_resource(self, *args):
    ''' return resource values as string or blank string '''
    resource = {}
    for key, value in args[0].iteritems():
        resource[key] = str(value).strip() if value != 'None' else ''
    return resource

所以我把san_resource['Resource Name']这是一个字符串赋给fresource[0].title,当我打印它时,它有时是unicode。上面print语句的输出示例:

^{pr2}$

如您所见,san_resource['Resource Name']始终是字符串,fresource[0].title是字符串,但有时是unicode。为什么会这样?我怎样才能修好它?在


Tags: 字符串nameinselfjsonobjforstring
1条回答
网友
1楼 · 发布于 2024-05-08 13:20:19

When I assign that string to a variable, the variable prints a unicode string

当您将该字符串传递给函数get_or_create()

fresource = FertilityResource.objects.get_or_create(
    title = san_resource['Resource Name'],
)

如果数据库中存在主键匹配的FertilityResource(大概是title),则从数据库返回现有的FertilityResource。在本例中,title将是Unicode字符串,因为所有Django ORM CharField属性都是本机的unicode。在

另一方面,如果数据库中没有现有实例,Django将用您给它的确切值创建一个新实例。在将实例放入数据库后,它不会麻烦地将其从数据库中取出,因此只剩下未被触及的str。在

^{pr2}$

这是干什么的?对于value中的非ASCII字符,它将失败。您应该尝试将所有字符串保持为unicode格式,这是处理JSON字符串和Django字符字段的文本和本机类型的正常方法。也许你想要这样的东西:

# Convert non-string types to strings
if not isinstance(value, basestring):
    value = unicode(value, 'utf-8', 'replace')
# Ignore special null value
if value == u'None':
    value = u''
resource[key] = value.strip()

相关问题 更多 >