Currently to add single quotes around a string, the best solution I came up with was to make a small wrapper function.
def foo(s1):
return "'" + s1 + "'"
Is there an easier more pythonic way of doing this?
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.
To quote a string in Python use single quotation marks inside of double quotation marks or vice versa. For instance: example1 = "He said 'See ya' and closed the door." example2 = 'They said "We will miss you" as he left.
In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .
If you want to use both single- and double-quotes without worrying about escape characters, you can open and close the string with three double-quotes or three single-quotes: print """In this string, 'I' can "use" either. """ print '''Same 'with' "this" string!
Just wanted to highlight what @metatoaster said in the comment above, as I missed it at first.
Using repr(string) will add single quotes, then double quotes outside of that, then single quotes outside of that with escaped inner single quotes, then onto other escaping.
Using repr(), as a built-in, 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\\\'"\''
The docs state its basically state repr(), i.e. representation, is the reverse of eval():
"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(),.."
Backquotes would be shorter, but are removed in Python 3+. Interestingly, StackOverflow uses backquotes to specify code spans, instead of highlighting a code block and clicking the code button - it has some interesting behavior though.
Here's another (perhaps more pythonic) option, using format strings:
def foo(s1):
return "'{}'".format(s1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With