简体   繁体   English

将列表转换为包含双引号并用逗号分隔的单个字符串

[英]convert a list into a single string consisting with double quotes and separated by comma

I have met a problem to convert a list: list=['1','2','3'] into ' "1","2","3" ' .我遇到了将列表转换为: list=['1','2','3']' "1","2","3" '问题。

My code is:我的代码是:

str(",".join('"{}"'.format(i) for i in list))

but my output is: "1","2","3" instead of ' "1","2","3" '但我的输出是: "1","2","3"而不是' "1","2","3" '

May I have your suggestion?我可以有你的建议吗? Thanks.谢谢。

I see you don't want to just prepend/append the needed substrings( the single quote and white space ) to the crucial string.我看到您不想只是将所需的子字符串(单引号和空格)添加/附加到关键字符串中。
Here's a trick with str.replace() function:这是str.replace()函数的一个技巧

lst = ['1','2','3']
result = "' - '".replace('-', ",".join('"{}"'.format(i) for i in lst))

print(result)

The output:输出:

' "1","2","3" '

  • "' - '" - acts as a placeholder "' - '" - 充当占位符

Or the same with additional str.format() function call:或与额外的str.format()函数调用相同:

result = "' {} '".format(",".join('"{}"'.format(i) for i in lst))
list = ['1','2','3', '5']
result = "' - '".replace('-', ",".join('"{}"'.format(i) for i in list)) 
# "' - '" - acts as a placeholder
print(result) # ' "1","2","3","5" '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Python列表中带单引号的字符串元素转为双引号 - How to convert string elements with single quotes to double quotes in a Python list Python字符串列表到1个字符串,用逗号和引号(,&“)分隔 - Python list of strings to 1 string separated by comma & quotes (, & ") 将逗号分隔的字符串转换为列表但忽略引号中的逗号 - Transform comma separated string into a list but ignore comma in quotes 如何将逗号分隔的字符串转换为用引号''括起来的每个单词到 python 中的列表? - How to convert a comma separated string with each word enclosed in quotes ' ' to a list in python? 如何将逗号分隔的字符串用引号括起来,用空格转换为带有单独元素的列表 - How to convert comma separated string enclosed in quotes, with spaces to a list with separate elements 将逗号分隔的浮点数转换为列表? - Convert comma separated string of floats into list? 将浮点数列表转换为逗号分隔的字符串 | Python - Convert list of floats to comma separated string | Python 将逗号分隔的字符串转换为 Python 中的列表项 - Convert comma separated string to list items in Python 将字典列表转换为逗号分隔的字符串 python - Convert list of Dictionaries to comma separated string python 如何用双引号列表转换单引号列表 - how to convert single quotes list with double quotes list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM