gpt4 book ai didi

python - unicode字符串格式

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:02 25 4
gpt4 key购买 nike

我刚刚在一段未注释的代码中看到了这一点。有理由这样做吗?

 new_var = u'%s' % (child.tag)

child 是一个实例,而 tag 是该实例的一个属性?看起来这样做更简单:

 new_var = unicode(child.tag)

最佳答案

它们是相同的,只是偏好问题。就 Python 之禅等而言,确实没有“更好”的方法,因为两者都是明确的,因为它们正在获得 child.tag 的 unicode 表示。他们机械地做同样的事情:

>>> class foo(object):
def __init__(self, val):
self.val = val

def __str__(self):
return "str: %s" % self.val
def __unicode__(self):
return "unicode: %s" % self.val


>>> f = foo("bar")
>>> u'%s' % f
u'unicode: bar'
>>> unicode(f)
u'unicode: bar'
>>> '%s' % f
'str: bar'

关于python - unicode字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5043730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com