Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么str.format()比str()好?_Python_String_Python 2.7_Format_String Formatting - Fatal编程技术网

Python 为什么str.format()比str()好?

Python 为什么str.format()比str()好?,python,string,python-2.7,format,string-formatting,Python,String,Python 2.7,Format,String Formatting,为了在python中将数字转换为字符串,我使用了str()函数,但有几个人建议我改用format()。当我尝试两者时,我得到了相同的结果: n = 10 print ['{}'.format(n)] # ['10'] print [str(n)] # ['10'] 有什么显著差异吗 While将为您提供数字的默认字符串表示形式,允许您指定其格式 示例: >>> '{:.3f}'.format(3.141592653589793) # 3 decimal places

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

n = 10  
print ['{}'.format(n)] # ['10']  
print [str(n)] # ['10']
有什么显著差异吗

While将为您提供数字的默认字符串表示形式,允许您指定其格式

示例:

>>> '{:.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'

格式字符串有许多不同的选项–完整的参考是。

我的答案会有点大胆…-)

我不认为
str.format()
str()
str()
更短,如果它能满足您的需求,那就太棒了

例如,如果您需要使用数字量格式化数字,则
{}.format()
将完成此工作,但
'%.3f“%n
也将完成此工作

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

Python本身似乎一直在寻找更好的方法,事实上,在Python3.6中,他们找到了迄今为止最好的方法IMO,这是一些编程语言所共有的。在这里,直接从文件:

>>> name = "Fred"
>>> f"He said his name is {name}."
您可以在此处阅读更多信息:


这家伙解释了
格式
str
的许多优点:

但是,如果时间是一个问题,您可能需要使用
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

我同意。我仍然使用℅ 在py34中,但一旦我可以使用py36,我将使用f类型。只要等待cython解决,您还可以使用嵌套格式:
'{:.{}f}.format(0.12345,5)->'0.12345'
'{:.{}f}.format(0.12345,2)->0.12