Force repr() to use single quotes

前端 未结 3 624
孤独总比滥情好
孤独总比滥情好 2020-12-19 17:31

I have a question, is there a way to \"force\" repr() to create always single quotes around a string?

This happens when I only use repr()

3条回答
  •  既然无缘
    2020-12-19 17:55

    I went ahead and implemented repr_double by using stdout's 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')
    

提交回复
热议问题