如何去掉字符串表示周围的单引号?
How to get rid of the single quotes around the representation of a string?
此示例代码打印文件中一行的表示形式。它允许在一行中查看其内容,包括 '\n'
等控制字符,因此我们将其称为该行的 "raw" 输出。
print("%r" % (self.f.readline()))
但是,输出显示的每一端都添加了 '
个不在文件中的字符。
'line of content\n'
如何去除输出周围的单引号?
(Python 2.7 和 3.6 中的行为相同。)
%r
采用字符串的 repr
表示。它可以根据需要转义换行符等,还可以添加引号。要解决此问题,请使用索引切片自行删除引号。
print("%s" %(repr(self.f.readline())[1:-1]))
如果这就是您要打印的全部内容,则根本不需要通过字符串格式化程序传递它
print(repr(self.f.readline())[1:-1])
这也有效:
print("%r" %(self.f.readline())[1:-1])
虽然这种方法有点矫枉过正,但在 Python 中,您可以子class 大多数(如果不是全部的话)内置类型,包括 str
。这意味着您可以定义自己的字符串 class ,其表示是您想要的任何内容。
以下说明如何使用该能力:
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)
输出:
s1: 'hello\nworld'
s2: hello\nworld
此示例代码打印文件中一行的表示形式。它允许在一行中查看其内容,包括 '\n'
等控制字符,因此我们将其称为该行的 "raw" 输出。
print("%r" % (self.f.readline()))
但是,输出显示的每一端都添加了 '
个不在文件中的字符。
'line of content\n'
如何去除输出周围的单引号?
(Python 2.7 和 3.6 中的行为相同。)
%r
采用字符串的 repr
表示。它可以根据需要转义换行符等,还可以添加引号。要解决此问题,请使用索引切片自行删除引号。
print("%s" %(repr(self.f.readline())[1:-1]))
如果这就是您要打印的全部内容,则根本不需要通过字符串格式化程序传递它
print(repr(self.f.readline())[1:-1])
这也有效:
print("%r" %(self.f.readline())[1:-1])
虽然这种方法有点矫枉过正,但在 Python 中,您可以子class 大多数(如果不是全部的话)内置类型,包括 str
。这意味着您可以定义自己的字符串 class ,其表示是您想要的任何内容。
以下说明如何使用该能力:
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)
输出:
s1: 'hello\nworld'
s2: hello\nworld