在Python2.7中为字符串添加单引号

2024-04-18 13:48:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用一个SQL输出字符串来使用Python查询PostgreSQL中的一些数据。我使用的是python2.7。你知道吗

例如:

The output string is mike
I want to have mike as 'mike' to be valid as an input.

这是我的密码:

formated_fix_names = ''.join(author_name_fix_list)).replace(' ', '\'')

问题是我需要将此字符串作为name = 'mike'传递给SQL代码:

cursor.execute("select author_name from commits where commit_hash in ("+formated_fix_names+")")

我想问题一定出在这一部分。你知道吗


Tags: theto数据字符串nameoutputsqlstring
3条回答

不要弄乱字符串操作。Psycopg通过adapting a Python ^{} to a Postgresql ^{}做正确的事情:

author_list = ['John','Mary']
query = """
    select author_name
    from commits
    where commit_hash = any (%s)
"""
print cursor.mogrify(query, (author_list,))
#cursor.execute(query, (author_list,))

输出:

select author_name
from commits
where commit_hash = any (ARRAY['John', 'Mary'])

注意,list必须传递给iterable中包装的^{}方法。你知道吗

如果list被强制转换为tuple,则可以使用in语法:

author_list = ['John','Mary']
query = """
    select author_name
    from commits
    where commit_hash in %s
"""
print cursor.mogrify(query, (tuple(author_list),))
#cursor.execute(query, (tuple(author_list),))

输出:

select author_name
from commits
where commit_hash in ('John', 'Mary')

如果要将字符串mike转换为字符串“mike”,可以使用以下表达式:

name = "mike"
newName = "'%s'" % name

这会将包含字符串mike的name转换为newName,其中包含字符串mike,并在其周围加上单引号,您现在应该可以使用它了。我希望这有帮助!你知道吗

可以使用双引号(""),例如:

name = "mike"
result = "'" + name + "'"

相关问题 更多 >