[英]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.