【问题标题】:What's the point of {0} placeholder{0} 占位符有什么意义
【发布时间】:2016-11-24 21:03:47
【问题描述】:

所以我目前正在学习一个 django+angular 教程,在其中,我的模型的 unicode 函数之一就是这个

def __unicode__(self):
    return '{0}'.format(self.content)

我的问题是为什么有必要使用这个占位符?我可以不只是这样做并达到相同的结果吗?

def __unicode__(self):
    return self.content

content 是一个文本字段

【问题讨论】:

  • return '{0}.format(self.content)'return '{0}'.format(self.content) 不同,这里可能有错别字。
  • 在你的情况下,你可以使用return self.content,当我们需要在另一个字符串中注入一些值时,我们使用format(),比如'Hello {}'.format(name)
  • 您实际上并不是在询问 占位符 本身。你在问为什么不能直接返回self.content

标签: python django tostring


【解决方案1】:

从技术上讲,一个类可以选择任意格式:

>>> class A:
...     def __format__(self, format_spec):
...         return 'foo'
...     def __str__(self):
...         return 'bar'
...         
>>> str(A())
'bar'
>>> '{0}'.format(A())
'foo'

Here are some tasty docs.

【讨论】:

    【解决方案2】:

    在这种情况下使用.format() 的原因是始终以字符串的形式返回content 的值,不管它是什么。例如:

    >>> '{0}'.format(1)   # `int`
    '1' 
    >>> '{0}'.format(1.01)  # `float`
    '1.01'
    >>> '{0}'.format(u'Hello')  # `unicode string`
    'Hello'
    

    否则,您最终将发送相同的值,保留实际 content 的类型。


    注意:我的回答假设问题中有错字,您的意思是'{0}'.format(self.content)而不是'{0}.format(self.content)'

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2018-03-14
      • 2014-07-23
      • 2011-11-10
      • 1970-01-01
      相关资源
      最近更新 更多