Python向triplequate字符串添加注释

2024-03-29 09:08:56 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在多行字符串中添加注释,或者不可能?我正试图从三引号字符串将数据写入csv文件。我在字符串中添加注释来解释数据。我尝试过这样做,但是Python只是假设注释是字符串的一部分。在

"""
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
"""

Tags: 文件ofcsvtheto数据字符串number
2条回答

如果将注释添加到字符串中,它们将成为字符串的一部分。如果这不是真的,你就永远不能在字符串中使用#字符,这将是一个非常严重的问题。在

但是,您可以对字符串进行后处理以删除注释,只要您知道这个特定的字符串不会有任何其他#字符。在

例如:

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)

如果还想删除#之前的尾随空格,请将regex更改为r'\s*#.*'。在

如果您不了解这些正则表达式是什么以及如何匹配的,请参见regex101以获得一个很好的可视化效果。在

如果您计划在同一个程序中多次执行此操作,您甚至可以使用类似于流行的D = textwrap.dedent习惯用法的技巧:

^{pr2}$

现在:

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
""")

不,不可能在字符串中包含注释。python如何知道字符串中的散列符号#应该是一个注释,而不仅仅是一个散列符号?将#字符解释为字符串的一部分比将其解释为注释更有意义。在


作为一种解决方法,您可以使用自动字符串文本连接:

(
"1,1,2,3,5,8,13\n" # numbers to the Fibonnaci sequence
"1,4,9,16,25,36,49\n" # numbers of the square number sequence
"1,1,2,5,14,42,132,429" # numbers in the Catalan number sequence
)

相关问题 更多 >