Skip to main content
 首页 » 编程设计

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

2025年05月04日18webabcd

我正在尝试通过 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) 

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