代码之家  ›  专栏  ›  技术社区  ›  Nathan

数组中的转义项(Python)

  •  0
  • Nathan  · 技术社区  · 8 年前
    >>> array = ['hello', 'world']
    >>> result = map(lambda item: `item`, array)
    >>> result
    ["'hello'", "'world'"]
    

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

    对于sql,我需要所有的东西都用记号来转义。

    我要找的结果是

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

    我这样做不是为了避免SQL注入,而是为了避免SQL保留字上的错误

    2 回复  |  直到 8 年前
        1
  •  1
  •   Austin    8 年前

    使用最新的 f -字符串:

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

    或者 format :

    result = ['`{}`'.format(item) for item in array]
    
        2
  •  0
  •   Gerges    8 年前

    我不知道,但这就是你想要的:

    array = ['hello', 'world']
    ['`' + s + '`' for s in array]
    
    Out[51]: ['`hello`', '`word`']
    

    或等效:

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