python - 将格式化文本存储在变量 python 中

标签 python string text string-formatting

我正在尝试通过 Python 脚本编写脚本文件

为此我定义了一个函数来打开、写入和关闭文件 def funcToCreateScript(文件名,文件内容)

我有另一个函数,我在其中调用 funcToCreateScript 并尝试通过变量将 shell 脚本内容传递给它。问题是当我如下格式化文本时

def createfile():
    var = """#!/bin/sh
             echo ${test}
          """
    funcToCreateScript(filename,var)

我得到的脚本输出为 -

#!/bin/sh
         echo ${test}

因此,它采用函数的缩进并相应地编写它。有没有办法格式化它,使其看起来像

#!/bin/sh
echo ${test}

例如-

def main():
    var = """
        #!/bin/sh
        echo ${test}
        """
    print var

main()

 > test.py

                #!/bin/sh
                echo ${test}

最佳答案

一种方法是使用 textwrap.dedent :

textwrap.dedent(text)

Remove any common leading whitespace from every line in text.

This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.

import textwrap

def createfile():
    var = """\
          #!/bin/sh
          echo ${test}
          """
    var = textwrap.dedent(var)
    funcToCreateScript(filename, var)

请注意,\ 紧跟在左三引号之后,以避免出现空行。

关于python - 将格式化文本存储在变量 python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654845/

相关文章:

c# - 追加到 txt 文件会产生奇怪的字符

R 将文本文件导入为数据框列表

python - 如何使用 Python 处理警报?

c++ - 如何从第二个字符开始传递一个字符串作为函数中的参数进行递归,并限制函数中的数据类型为字符串?

python - 从 Python 的子进程调用 scp 不适用于文件列表\{a,b,c\}

C#:从字符串中删除多余的文本

python - 寻找 pyplot.plot() 的标记文本选项

python - Scrapy 将两个蜘蛛放在一个文件中

python - 如何卡住仅在虚拟环境中安装的软件包?

python - PYODBC ProgrammingError : ('42000' , “[42000] [Microsoft][Pilote ODBC Microsoft Access]