繁体   English   中英

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

[英]Python - Adding comments into a triple-quote string

有没有办法将注释添加到多行字符串中,还是不可能? 我正在尝试从三引号字符串将数据写入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如何知道字符串中的井号#应该是注释,而不仅仅是井号? #字符解释为字符串的一部分比解释为注释更有意义。


解决方法是,可以使用自动字符串文字串联:

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

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

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

例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM