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
)
如果您在字符串中添加注释,它们将成为字符串的一部分。如果不是这样,您将永远无法在字符串中使用 #
字符,这将是一个非常严重的问题。
但是,您可以 post-process 该字符串删除注释,只要您知道该特定字符串不会包含任何其他 #
个字符。
例如:
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
""")
有没有办法在多行字符串中添加注释,或者这不可能?我正在尝试将数据从三引号字符串写入 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
)
如果您在字符串中添加注释,它们将成为字符串的一部分。如果不是这样,您将永远无法在字符串中使用 #
字符,这将是一个非常严重的问题。
但是,您可以 post-process 该字符串删除注释,只要您知道该特定字符串不会包含任何其他 #
个字符。
例如:
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
""")