强制repr()使用单引号 [英] Force repr() to use single quotes
本文介绍了强制repr()使用单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
repr()
在字符串周围创建一个单引号? 当我只使用 repr()
print repr(test)
'test'
print repr(test')
test
print repr(test\
'test''
print repr(test'\)
'test \'''
所以最后一个实际上是我想要的,但我不想总是添加 \\
解决方案
嗯,如果你的对象总是一个字符串,你可以这样做:
def repr_single(s):
return'+ repr('''+ s)[2:]
print repr_single(test')
'test \''
但正如Martijn Pieters所说,我对这里的用例很好奇。
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()
print repr("test")
'test'
print repr("test'")
"test'"
print repr("test\"")
'test"'
print repr("test'\"")
'test\'"'
so the last one actually does, what I want, but I don't want to add always \\"
to get the single quotes.
解决方案
Well, if your object is always a string you could do this:
def repr_single(s):
return "'" + repr('"' + s)[2:]
print repr_single("test'")
'test\''
But as Martijn Pieters asked I'm curious as to your use case here.
这篇关于强制repr()使用单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文