循环使用模板安全替代函数

问题描述 投票:0回答:1

我有这个简单的代码:

  html_string = '''<html lang="en-US">
            '<head> 
                <title>My Python articles</title>
            </head>
            <body>'''
    for i in range(2):
        html_string += '''
                <p>
                    <span style="white-space: pre-line">$''' + str(i) + '''</span>
                </p>'''

    html_string += '''</body>
        </html>'''

    html_template = Template(html_string)

    output_dir = "./html/"
    output_path = os.path.join(output_dir, 'my_page.html')
    with io.open(output_path, 'w+', encoding='UTF-8', errors='replace') as html_output:
        for i in range(2):
            html_output.write(html_template.safe_substitute(i="Hallo"))
            html_output.truncate()

i中的html_output.write(html_template.safe_substitute(i="Hello"))似乎与for循环中的i不对应,我得到的只是:

$0

$1

$0

$1  

$0$1仅需要存在一次,并且每个都必须用单词[[Hello代替。稍后,我将用不同的输入替换$0$1

python string
1个回答
1
投票
模板字符串的docs具有关于替换标识符的说法:

默认情况下,“标识符”仅限于任何以下划线或ASCII字母开头的不区分大小写的ASCII字母数字字符串(包括下划线)。

诸如“ $ 0”和“ $ 1”之类的标识符不满足此条件,因为它们以ASCII

digit开头。

在这样的数字和“ $”之间插入字母应该起作用:

html_string = '''<html lang="en-US"> '<head> <title>My Python articles</title> </head> <body>''' # Make substitution identifiers like "$Ti" for i in range(2): html_string += ''' <p> <span style="white-space: pre-line">$T''' + str(i) + '''</span> </p>''' html_string += '''</body> </html>''' html_template = Template(html_string) # Map identifiers to values mapping = {'T' + str(i): 'Hello' for i in range(2)} output_dir = "./html/" output_path = os.path.join(output_dir, 'my_page.html') with open(output_path, 'w+', encoding='UTF-8', errors='replace') as html_output: html_output.write(html_template.safe_substitute(mapping)) html_output.truncate()

© www.soinside.com 2019 - 2024. All rights reserved.