pyCthon
pyCthon

Reputation: 12341

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?

Upvotes: 13

Views: 59857

Answers (4)

NewAgeA
NewAgeA

Reputation: 61

This works on Python 3.5+

def foo2(char):
    return("'{}'".format(char))

Upvotes: 2

alchemy
alchemy

Reputation: 982

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.

Upvotes: 13

Krypton
Krypton

Reputation: 3325

What about:

def foo(s1):
    return "'%s'" % s1

Upvotes: 15

Óscar López
Óscar López

Reputation: 236004

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

def foo(s1):
    return "'{}'".format(s1)

Upvotes: 16

Related Questions