Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python2.7中向字符串添加单引号_Python_Postgresql_Casting_Parameter Passing_Psycopg2 - Fatal编程技术网

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

在Python2.7中向字符串添加单引号,python,postgresql,casting,parameter-passing,psycopg2,Python,Postgresql,Casting,Parameter Passing,Psycopg2,我想使用SQL输出字符串来使用Python查询PostgreSQL中的一些数据。我正在使用Python 2.7 例如: name = "mike" result = "'" + name + "'" 输出字符串为mike 我想让mike作为'mike'作为有效的输入 这是我的代码: formated_fix_names = ''.join(author_name_fix_list)).replace(' ', '\'') 问题是我需要将此字符串作为name='mike'传递给SQL代码: c

我想使用SQL输出字符串来使用Python查询PostgreSQL中的一些数据。我正在使用Python 2.7

例如:

name = "mike"
result = "'" + name + "'"
输出字符串为
mike

我想让
mike
作为
'mike'
作为有效的输入

这是我的代码:

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+")")
问题一定出在这一部分,我想替换(“”,“\”)您可以使用双引号(
),例如:

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

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

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

这会将包含字符串mike的name转换为newName,其中包含带单引号的字符串mike,您现在应该可以使用它了。我希望这有帮助

不要干扰字符串操作。正确的做法是:

输出:

select author_name
from commits
where commit_hash = any (ARRAY['John', 'Mary'])
select author_name
from commits
where commit_hash in ('John', 'Mary')
请注意,
列表
必须传递给用iterable包装的方法

如果将
列表
转换为
元组
,则可以使用
中的

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 = any (ARRAY['John', 'Mary'])
select author_name
from commits
where commit_hash in ('John', 'Mary')

我认为这部分应该做些什么。替换(“”,“”,“”)请在代码前用4个空格将代码格式化为可读格式,查看更多详细信息。不,此语法
formatted\u fix\u hashes=“”。join(fix\u list)。replace(“[”,“”)。replace(“,”)。replace(“\”,“\”)
用于转换[“80f3bcb58f836cfe”]在“80f3bcb58f836cfe”中,问题是
”。加入(作者名称\u修复列表))
,尝试删除最后一个