擅长:python、mysql、java
<p>如果我们的目标是拥有一个非常通用的工具来打印(或写入文件)字符串,这些字符串稍后可以被Python重新解析,那么如果您正在编写的数据还可能包含带有嵌入三引号的字符串,那么您应该小心不要使用@TigerhawkT3提供的答案。答案的变体可用于确保任何带三个单引号的嵌入字符串正确转义:</p>
<pre><code>>>> mylist = ['hi there', 'foo bar', '"""', "'''", '"', "''"]
>>> print("'''{}'''".format(mylist))
'''['hi there', 'foo bar', '"""', "'''", '"', "''"]'''
>>> print("'''{}'''".format('{}'.format(mylist).replace("'''", r"\'\'\'")))
'''['hi there', 'foo bar', '"""', "\'\'\'", '"', "''"]'''
</code></pre>