在python中为字符串添加双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38535707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add double quotes to string in python
提问by qwertylpc
If my input text is
如果我的输入文本是
a
b
c
d
e
f
g
and I want my output text to be: (with the double quotes)
我希望我的输出文本是:(带双引号)
"a b c d e f g"
Where do I go after this step:
这一步之后我要去哪里:
" ".join([a.strip() for a in b.split("\n") if a])
回答by James
You have successfully constructed a string without the quotes. So you need to add the double quotes. There are a few different ways to do this in Python:
您已成功构建了一个不带引号的字符串。所以你需要添加双引号。在 Python 中有几种不同的方法可以做到这一点:
>>> my_str = " ".join([a.strip() for a in b.split("\n") if a])
>>> print '"' + my_str + '"' #Use single quotes to surround the double quotes
"a b c d e f g"
>>> print "\"" + my_str + "\"" #Escape the double quotes
"a b c d e f g"
>>> print '"%s"'%my_str #Use string formatting
"a b c d e f g"
Any of these options are valid and idiomatic Python. I might go with the first option myself simply because it's short and clear
这些选项中的任何一个都是有效且惯用的 Python。我可能会自己选择第一个选项,因为它简短明了
回答by CentAu
'"%s"' % " ".join([a.strip() for a in s.split("\n") if a])