Python - 将注释添加到三引号字符串中

问题描述 投票:0回答:2

有没有办法将注释添加到多行字符串中,还是不可能?我正在尝试从三引号字符串中将数据写入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
"""
python string python-3.x comments multiline
2个回答
0
投票

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

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

例如:

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)

如果您还想在#之前删除尾随空格,请将正则表达式更改为r'\s*#.*'

如果您不理解这些正则表达式匹配的内容以及如何匹配,请参阅regex101以获得良好的可视化效果。

如果你计划在同一个程序中多次这样做,你甚至可以使用类似于流行的D = textwrap.dedent成语的技巧:

C = functools.partial(re.sub, r'#.*', '')

现在:

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

2
投票

不,不可能在字符串中添加注释。 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
)
© www.soinside.com 2019 - 2024. All rights reserved.