Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.X adding single quotes around a string

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?

like image 371
pyCthon Avatar asked Apr 09 '14 04:04

pyCthon


People also ask

How do I put single quotes around text in Python?

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.

How do you concatenate a single quote from a string in Python?

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.

How do you surround a string with double quotes in Python?

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 \" .

How do you print double and single quotes in Python?

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!


2 Answers

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.

like image 62
alchemy Avatar answered Sep 21 '22 16:09

alchemy


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

def foo(s1):
    return "'{}'".format(s1)
like image 40
Óscar López Avatar answered Sep 20 '22 16:09

Óscar López