Skip to main content
 首页 » 编程设计

python之在 python 中使用 str.format 时的引号

2025年05月04日18小虾米

当使用 str.format 在 python 2.7.6 中输出时,如下所示:

>>> "| {0: ^18} | {1: ^18} |".format(1, 0.001) 

结果:

'|         1          |       0.001        |' 

我想知道如何抑制输出字符串两端的单引号。

请您参考如下方法:

引号不是格式语句返回值的一部分,它们来自 python 解释器,告诉你它正在显示一个字符串值:

momerath:~ mgregory$ python 
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)  
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> "| {0: ^18} | {1: ^18} |".format(1, 0.001) 
'|         1          |       0.001        |' 
>>> print "| {0: ^18} | {1: ^18} |".format(1, 0.001) 
|         1          |       0.001        | 
>>> a = 1 
>>> a 
1 
>>> a = "foo" 
>>> a 
'foo' 
>>> print a 
foo 
>>>  

... 所以如果您只想查看字符串的值,只需打印它即可。

我不知道有什么方法可以让 python 解释器在报告字符串结果时不要引用它们。