Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Force repr() to use single quotes

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.


Edit: I am not going to mark an answer as accepted since, as pointed out by @martijn-pieters, I was using repr() for purposes it is not intended for.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...