Nathan
Nathan

Reputation: 56

Escaping items in an array (Python)

>>> 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

Upvotes: 0

Views: 605

Answers (2)

Gerges
Gerges

Reputation: 6499

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`']

Upvotes: 0

Austin
Austin

Reputation: 26039

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]

Upvotes: 1

Related Questions