简体   繁体   中英

quotes when using str.format in python

When using str.format to output in python 2.7.6 such as below:

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

This results:

'|         1          |       0.001        |'

I am wondering how to suppress the single quotes on either end of the output string.

The quotes are not part of the return value of the format statement, they are coming from the python interpreter, telling you that it is showing you a string value:

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
>>> 

... so if you want to see only the value of a string, simply print it.

I'm not aware of a way to ask the python interpreter not to quote string results when it reports them.

Rising to the challenge of GreenAsJade, and another attempt at directly answering the question by monkey-patching a subclass of str that will echo the str representation on the REPL.

class SillyString(str):
    def __repr__(self):
        return self.__str__()

Instantiate the string:

>>> foo = SillyString('foo')

And have it echoed on the Python shell:

>>> foo
foo

contrasted with the standard Python str:

>>> 'foo'
'foo'

GreenAsJade has a good answer (+1), but I'll see if I can improve on it.

The interpreter is merely echoing the literal in the REPL by printing the __repr__ of the object, a string which if printed should show an unambiguous representation of the object. So to remove the end quotes (and thus the unambiguous object representation), print the object:

>>> ['foo'].__repr__()
"['foo']"

>>> 'foo'.__repr__()
"'foo'"

>>> print 'foo'.__repr__()
'foo'

>>> print 'foo'
foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM