Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.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
将python字符串转换为带引号字符串的简单方法_Python - Fatal编程技术网

将python字符串转换为带引号字符串的简单方法

将python字符串转换为带引号字符串的简单方法,python,Python,我是python新手,我有一个select语句,如下面的help\u category\u id,name,将此字符串转换为此字符串的最有效方法是什么: 'help_category_id', 'name' 我目前已经这样做了,效果很好,但是有没有更好更干净的方法来做到这一点: test_string = 'help_category_id, name' column_sort_list = [] if test_string is not None: for col in test_

我是python新手,我有一个select语句,如下面的
help\u category\u id,name
,将此字符串转换为此字符串的最有效方法是什么:

'help_category_id', 'name'
我目前已经这样做了,效果很好,但是有没有更好更干净的方法来做到这一点:

test_string = 'help_category_id, name'
column_sort_list = []
if test_string is not None:
    for col in test_string.split(','):
        column = "'{column}'".format(column=col)
        column_sort_list.append(column)
column_sort = ','.join(column_sort_list)
print(column_sort)

使用循环构造的简单一行程序:

result = ", ".join(["'" + i + "'" for i.strip() in myString.split(",")])
我们在这里做的是创建一个列表,其中包含原始字符串的所有子字符串,并添加引号。然后,使用
join
,我们将该列表生成一个逗号分隔的字符串

解构后,循环构造如下所示:

resultList = []
for i in myString.split(","):
    resultList.append("'" + i.strip() + "'")
注意对
i.strip()
的调用,它删除了每个子字符串周围的多余空格

注意:您可以使用格式语法使此代码更加清晰:

新语法:

result = ", ".join(["'{}'".format(i.strip()) for i in myString.split(",")])
result = ", ".join(["'%s'" % i.strip() for i in myString.split(",")])
旧语法:

result = ", ".join(["'{}'".format(i.strip()) for i in myString.split(",")])
result = ", ".join(["'%s'" % i.strip() for i in myString.split(",")])

这也是可以实现的

','.join("'{}'".format(value) for value in map(lambda text: text.strip(), test_string.split(",")))

好的,字符串可以用
分隔,也可以用空格
分隔,我如何确保两者都是catched@PeterPik你是说它只能用空格分隔,还是用逗号和空格分隔?如果是后者,那么我的代码已经说明了这一点。它可以用逗号和空格分隔,就像sql中的逗号一样statement@PeterPik该代码同时适用于逗号和逗号与空格(甚至混合在同一个字符串中)。哦,只是想
“,”。join
只使用逗号和空格连接