【问题标题】:Why is str.format() better than str()?为什么 str.format() 比 str() 好?
【发布时间】:2017-06-30 07:45:44
【问题描述】:

为了在 python 中将数字转换为字符串,我使用了str() 函数,但有些人建议我改用format()。当我尝试两者时,我得到了相同的结果:

n = 10  
print ['{}'.format(n)] # ['10']  
print [str(n)] # ['10']

有什么明显的区别吗?

【问题讨论】:

    标签: python string python-2.7 format string-formatting


    【解决方案1】:

    这家伙解释了format 相对于str 的许多优点: https://pyformat.info/

    但是,如果您担心时间问题,您可能希望使用str

    >>> import timeit
    >>> timeit.timeit('str(25)', number=10000)
    0.003485473003820516
    >>> timeit.timeit('"{}".format(25)', number=10000)
    0.00590304599609226
    >>> timeit.timeit('str([2,5])', number=10000)
    0.007156646002840716
    >>> timeit.timeit('"{}".format([2,5])', number=10000)
    0.017119816999183968
    

    【讨论】:

      【解决方案2】:

      我的回答会有点大胆.. :-)

      我不认为str.format()str() 更好。 str() 更短,如果它能给你想要的,那就太好了。

      如果您需要使用位数来格式化数字,例如,{}.format() 可以完成这项工作,但'%.3f' % n 也可以完成这项工作。

      % 运算符相比,{}.format() 有一些优势,重复参数是其中之一,但并不常见。我仍然使用%,因为它更短。

      Python 本身似乎一直在寻找更好的方法,事实上,在 Python 3.6 中,他们已经提出了迄今为止最好的方法,即 IMO,这对于某些编程语言来说很常见。直接来自文档:

      >>> name = "Fred"
      >>> f"He said his name is {name}."
      

      您可以在此处阅读更多信息:

      https://www.python.org/dev/peps/pep-0498/

      【讨论】:

      • 我同意。我仍然在 py34 中使用℅,但是一旦我可以使用 py36,我将使用 f 类型。只是等待 cython 解决
      【解决方案3】:

      str() 将为您提供数字的默认字符串表示形式,str.format() 允许您指定其格式。

      例子:

      >>> '{:.3f}'.format(3.141592653589793)  # 3 decimal places
      '3.142'
      
      >>> '{:,d}'.format(1234567)  # thousand separators
      '1,234,567'
      
      
      >>> '{:6d}'.format(10)  # padded to six spaces
      '    10'
      
      >>> '{:05.2f}%'.format(8.497)  # zero-padded, 2 decimal places
      '08.50%'
      
      >>> '{:^6d}'.format(10)  # centered
      '  10  '
      
      >>> '{:x}'.format(1597463007)  # hexadecimal
      '5f3759df'
      

      您还可以指定涉及多个值的格式字符串:

      >>> 'Customer #{cust_id:08d} owes ${bal:,.2f}'.format(bal=1234.5, cust_id=6789)
      'Customer #00006789 owes $1,234.50'
      

      格式字符串有很多不同的选项——完整的参考是here

      【讨论】:

      • 您还可以有嵌套格式:'{:.{}f}'.format(0.12345, 5) -> '0.12345''{:.{}f}'.format(0.12345, 2) -> 0.12
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 2016-08-22
      • 2018-01-04
      • 2012-04-09
      • 2011-09-04
      • 2020-04-27
      • 2011-01-04
      相关资源
      最近更新 更多