简体   繁体   中英

How to get rid of the single quotes around the representation of a string?

This sample code prints the representation of a line from a file. It allows its contents to be viewed, including control characters like '\\n' , on a single line—so we refer to it as the "raw" output of the line.

print("%r" % (self.f.readline()))

The output, however, appears with ' characters added to each end which aren't in the file.

'line of content\\n'

How to get rid of the single quotes around the output?
(Behavior is the same in both Python 2.7 and 3.6.)

%r takes the repr representation of the string. It escapes newlines and etc. as you want, but also adds quotes. To fix this, strip off the quotes yourself with index slicing.

print("%s" %(repr(self.f.readline())[1:-1]))

If this is all you are printing, you don't need to pass it through a string formatter at all

print(repr(self.f.readline())[1:-1])

This also works:

print("%r" %(self.f.readline())[1:-1])

Although this approach would be overkill, in Python you can subclass most, if not all, of the built-in types, including str . This means you could define your own string class whose representation is whatever you want.

The following illustrates using that ability:

class MyStr(str):
    """ Special string subclass to override the default representation method
        which puts single quotes around the result.
    """
    def __repr__(self):
        return super(MyStr, self).__repr__().strip("'")

s1 = 'hello\nworld'
s2 = MyStr('hello\nworld')

print("s1: %r" % s1)
print("s2: %r" % s2)

Output:

s1: 'hello\nworld'
s2: hello\nworld

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