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

TMWP picture TMWP · Mar 23, 2017 · Viewed 8.2k times · Source

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

Answer

tdelaney picture tdelaney · Mar 23, 2017

%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])