0
>>> array = ['hello', 'world']
>>> result = map(lambda item: `item`, array)
>>> result
["'hello'", "'world'"]

or

>>> result = [`item` for item in array]
>>> result
["'hello'", "'world'"]

For sql I need everything escaped with ticks.

The result I am looking for is

["`hello`", "`world`"]

I'm not doing this to avoid SQL injection, im doing this to avoid errors on SQL reserved words

3
  • 2
    Side-note: map(lambda item: `item`, array) is a deprecated and slower way to spell map(repr, array). Backticks are just a syntactic way to get the repr of an item, and it's deprecated (removed in Python 3). Commented Aug 16, 2018 at 17:09
  • In any event, doing this safely (to avoid SQL injection attacks) is harder than just adding backticks to the string. Use whatever parameterized query syntax your SQL library supports; you will always get manual escaping wrong, and parameterized queries can be more efficient to boot, so use them. Commented Aug 16, 2018 at 17:11
  • If you're already building queries, why not use a proper query builder: sqlalchemy.org Commented Aug 16, 2018 at 17:41

2 Answers 2

1

Use the newest f-strings:

array = ['hello', 'world']
result = [f'`{item}`' for item in array]

print(result)
# ['`hello`', '`world`']

Or format:

result = ['`{}`'.format(item) for item in array]
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure I get it, but is this what you are looking for:

array = ['hello', 'world']
['`' + s + '`' for s in array]

Out[51]: ['`hello`', '`word`']

or equivalently:

list(map(lambda x: '`{}`'.format(x), array))
Out[53]: ['`hello`', '`word`']

1 Comment

lambda x: '`{}`'.format(x) is a slow way to spell '`{}`'.format; I know people love lambdas, but methods and functions are first class objects, you can just use them directly. map(lambda x: '`{}`'.format(x), array) could become map('`{}`'.format, array)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.