Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 547
TMWP Avatar asked Mar 23 '17 20:03

TMWP


2 Answers

%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])
like image 179
tdelaney Avatar answered Nov 14 '22 23:11

tdelaney


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
like image 36
martineau Avatar answered Nov 14 '22 21:11

martineau