我有个问题,有没有办法“强制”repr()在字符串周围创建单引号?
当我只使用repr()时会发生这种情况
print repr("test")
'test'
print repr("test'")
"test'"
print repr("test\"")
'test"'
print repr("test'\"")
'test\'"'最后一个是我想要的,但我不想总是添加\\"来得到单引号。
编辑:,我不会将答案标记为已被接受,因为正如@martijn所指出的,我使用repr()的目的并不是为了它的目的。
发布于 2014-12-10 19:57:14
如果您的对象总是一个字符串,您可以这样做:
def repr_single(s):
return "'" + repr('"' + s)[2:]
print repr_single("test'")
'test\''但是,正如所问的,我对这里的用例很好奇。
发布于 2015-06-12 15:45:30
我曾经需要做类似的事情,但我希望它总是“更喜欢”使用双引号--意思是使用双引号,除非字符串中的双引号比单引号多(以尽量减少需要转义的单引号)。
我这样做的方法是对内置的str类进行子类化,并重写它的__repr__()方法。您可能会很容易地将它中的逻辑反转到相反的位置(以及强制使用的字符总是一个或另一个字符)。
FWIW,代码如下:
# -*- coding: iso-8859-1 -*-
# Special string subclass to override the default
# representation method. Main purpose is to
# prefer using double quotes and avoid hex
# representation on chars with an ord() > 128
class MsgStr(str):
def __repr__(self):
# use double quotes unless there are more of them in the string than
# single quotes
quotechar = '"' if self.count("'") >= self.count('"') else "'"
rep = [quotechar]
for ch in self:
# control char?
if ord(ch) < ord(' '):
# remove the single quotes around the escaped representation
rep += repr(str(ch)).strip("'")
# does embedded quote match quotechar being used?
elif ch == quotechar:
rep += "\\"
rep += ch
# else just use others as they are
else:
rep += ch
rep += quotechar
return "".join(rep)
if __name__ == "__main__":
s1 = '\tWürttemberg'
s2 = MsgStr(s1)
print "str s1:", s1
print "MsgStr s2:", s2
print "--only the next two should differ--"
print "repr(s1):", repr(s1), "# uses built-in string 'repr'"
print "repr(s2):", repr(s2), "# uses custom MsgStr 'repr'"
print "str(s1):", str(s1)
print "str(s2):", str(s2)
print "repr(str(s1)):", repr(str(s1))
print "repr(str(s2)):", repr(str(s2))
print "MsgStr(repr(MsgStr('\tWürttemberg'))):", MsgStr(repr(MsgStr('\tWürttemberg')))
assert eval(MsgStr(repr(MsgStr('\tWürttemberg')))) == MsgStr('\tWürttemberg')输出:
str s1: Württemberg
MsgStr s2: Württemberg
--only the next two should differ--
repr(s1): '\tW\xfcrttemberg' # uses built-in string 'repr'
repr(s2): "\tWürttemberg" # uses custom MsgStr 'repr'
str(s1): Württemberg
str(s2): Württemberg
repr(str(s1)): '\tW\xfcrttemberg'
repr(str(s2)): '\tW\xfcrttemberg'
MsgStr(repr(MsgStr(' Württemberg'))): "\tWürttemberg"发布于 2018-03-22 17:51:14
我使用stdout的repr_double实现了repr_single
def repr_single(s):
return "'" + repr('"' + s)[2:]
def repr_double(s):
single = repr_single(s)
return '"' + single[1:-1].replace('"', '\\"').replace('\\\'', '\'') + '"'
def test_single():
assert r"'foobar'" == repr_single('foobar')
assert r"'\'foobar'" == repr_single('\'foobar')
assert "'\\'foobar'" == repr_single("'foobar")
def test_double():
assert r'"foobar"' == repr_double("foobar")
assert '"\'foobar"' == repr_double("'foobar")
assert '"\\"foobar"' == repr_double('"foobar')https://stackoverflow.com/questions/27402168
复制相似问题