擅长:python、mysql、java
<p>如果将注释添加到字符串中,它们将成为字符串的一部分。如果这不是真的,你就永远不能在字符串中使用<code>#</code>字符,这将是一个非常严重的问题。在</p>
<p>但是,您可以对字符串进行后处理以删除注释,只要您知道这个特定的字符串不会有任何其他<code>#</code>字符。在</p>
<p>例如:</p>
<pre><code>s = """
1,1,2,3,5,8,13 # numbers to the Fibonnaci sequence
1,4,9,16,25,36,49 # numbers of the square number sequence
1,1,2,5,14,42,132,429 # numbers in the Catalan number sequence
"""
s = re.sub(r'#.*', '', s)
</code></pre>
<p>如果还想删除<code>#</code>之前的尾随空格,请将regex更改为<code>r'\s*#.*'</code>。在</p>
<p>如果您不了解这些正则表达式是什么以及如何匹配的,请参见<a href="https://regex101.com/r/131Gin/1" rel="nofollow noreferrer">regex101</a>以获得一个很好的可视化效果。在</p>
<p>如果您计划在同一个程序中多次执行此操作,您甚至可以使用类似于流行的<code>D = textwrap.dedent</code>习惯用法的技巧:</p>
^{pr2}$
<p>现在:</p>
<pre><code>s = C("""
1,1,2,3,5,8,13 # numbers to the Fibonnaci sequence
1,4,9,16,25,36,49 # numbers of the square number sequence
1,1,2,5,14,42,132,429 # numbers in the Catalan number sequence
""")
</code></pre>