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

标签 python string python-3.x comments multiline

有没有办法将注释添加到多行字符串中,或​​者不可能?我正在尝试将数据从三引号字符串写入 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
)

关于Python - 将注释添加到三引号字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49662174/

相关文章:

Python逐行检查列表

python - 根据Python3中的值传递可选参数

string - 在 Scala 中高效地重复字符/字符串 n 次

python - 从同一文件夹中的文件导入功能

python-3.x - 多线程爬虫运行一段时间后越来越慢

python - 如何在Python中正确传递参数

python - Python 代码可以像 Javascript 一样被压缩吗?

python - 如何在Python中用前面的数字分割utf-8字符串?

c++ - 从 std::string 中删除特定的连续字符重复

Python Ctypes : convert list of integers to array of shorts