如果我的输入文字是
a
b
c
d
e
f
g
我希望我的输出文本为:(带双引号)
"a b c d e f g"
此步骤后我要去哪里:
" ".join([a.strip() for a in b.split("\n") if a])
您已经成功构造了不带引号的字符串。因此,您需要添加双引号。在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 old-style string formatting
"a b c d e f g"
>>> print '"{}"'.format(my_str) # Use the newer format method
"a b c d e f g"
或在Python 3.6+中:
>>> print(f'"{my_str}"') # Use an f-string
"a b c d e f g"
这些选项中的任何一个都是有效且惯用的Python。我可能自己选择第一个选项,或者选择Python 3中的最后一个选项,仅因为它们是最短和最清晰的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句