首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >强制repr()使用单引号

强制repr()使用单引号
EN

Stack Overflow用户
提问于 2014-12-10 13:24:37
回答 3查看 2.9K关注 0票数 5

我有个问题,有没有办法“强制”repr()在字符串周围创建单引号?

当我只使用repr()时会发生这种情况

代码语言:javascript
复制
print repr("test")
'test'
print repr("test'")
"test'"
print repr("test\"")
'test"'
print repr("test'\"")
'test\'"'

最后一个是我想要的,但我不想总是添加\\"来得到单引号。

编辑:,我不会将答案标记为已被接受,因为正如@martijn所指出的,我使用repr()的目的并不是为了它的目的。

EN

回答 3

Stack Overflow用户

发布于 2014-12-10 19:57:14

如果您的对象总是一个字符串,您可以这样做:

代码语言:javascript
复制
def repr_single(s):
    return "'" + repr('"' + s)[2:]

print repr_single("test'")
'test\''

但是,正如所问的,我对这里的用例很好奇。

票数 4
EN

Stack Overflow用户

发布于 2015-06-12 15:45:30

我曾经需要做类似的事情,但我希望它总是“更喜欢”使用双引号--意思是使用双引号,除非字符串中的双引号比单引号多(以尽量减少需要转义的单引号)。

我这样做的方法是对内置的str类进行子类化,并重写它的__repr__()方法。您可能会很容易地将它中的逻辑反转到相反的位置(以及强制使用的字符总是一个或另一个字符)。

FWIW,代码如下:

代码语言:javascript
复制
# -*- 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')

输出:

代码语言:javascript
复制
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"
票数 2
EN

Stack Overflow用户

发布于 2018-03-22 17:51:14

我使用stdout的repr_double实现了repr_single

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27402168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档