Python 2.X adds single quotes around a string

Currently, to add single quotes around the string, the best solution I came up with was to create a small wrapper function.

def foo(s1): return "'" + s1 + "'" 

Is there an easier way for pythonic?

+8
python
source share
3 answers

What about:

 def foo(s1): return "'%s'" % s1 
+12
source share

Here's another (possibly more pythonic) option using format strings :

 def foo(s1): return "'{}'".format(s1) 
+10
source share

Just wanted to emphasize what @metatoaster said in the comment above, since I skipped it first.

Using repr (string) will add single quotes, then double quotes outside of it, then single quotes outside of it with escaped internal single quotes, and then to another escaping.

Using repr () as an inline function is more direct, unless there are other conflicts.

 s = 'strOrVar' print s, repr(s), repr(repr(s)), ' ', repr(repr(repr(s))), repr(repr(repr(repr(s)))) # prints: strOrVar 'strOrVar' "'strOrVar'" '"\'strOrVar\'"' '\'"\\\'strOrVar\\\'"\'' 

docs states that its main expression is state (), i.e. the view is the reverse of eval ():

"For many types, this function tries to return a string that will give an object with the same value when passed to eval (), ..."

Backquotes will be shorter but removed in Python 3+. Interestingly, StackOverflow uses backquotes to specify code spaces, instead of highlighting a block of code and pressing a code button - it has an interesting behavior.

+8
source share

All Articles