如何在多行字符串变量中写入多个变量?

时间:2020-06-02 10:08:35

标签: python python-3.x

我正在尝试制作一个简单的脚本,以便能够将每种字体打印到CSS @font-face

因此,对于特定目录中的每种字体,都应打印:

@font-face {
  font-family: "fontName1", sans-serif;
  src: url("http://localhost/wp-content/themes/theme/fonts/fontName1.ttf");
  font-weight: normal;
}

@font-face {
  font-family: "fontName2", sans-serif;
  src: url("http://localhost/wp-content/themes/theme/fonts/fontName2.ttf");
  font-weight: normal;
}

等...

现在,这就是我尝试过的:

import glob

fontFiles = []

for file in glob.glob("*.ttf"):
    cssRule = """
        @font-face {
            font-family: "{fontName}", sans-serif;
            src: url("http://localhost/wp-content/themes/theme/fonts/{fontFile}");
            font-weight: normal;
        }
    """.format(fontName=file[:-4], fontFile=file)
    print(cssRule)

运行脚本时出现以下错误:

Traceback (most recent call last File ".\script.py", line 6, in <cssRule = KeyError: '\n            font-family'

我不知道我在做什么错?这是因为python脚本中的format吗?在多行字符串变量中写入多个变量的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

用大括号括起来,这是为了在字符串文字中用空格括起来的字符, string_formatting

for file in glob.glob("*.ttf"):
    cssRule = """
        @font-face {{
            font-family: "{fontName}", sans-serif;
            src: url("http://localhost/wp-content/themes/theme/fonts/{fontFile}");
            font-weight: normal;
        }}
    """.format(fontName=file[:-4], fontFile=file)
    print(cssRule)