Python:2.4 格式字符串不工作

标签 python

我原来的 2.7 代码在这里:

            myFile = open(prjFile, 'w+')
            myFile.write("""<VirtualHost 192.168.75.100:80>
    ServerName www.{hostName}
    ServerAlias {hostNameshort}.* www.{hostNameshort}.*
    DocumentRoot {prjDir}/html
    CustomLog \\|/usr/sbin/cronolog /var/log/httpd/class/{prjCode}/\{hostName}.log.%Y%m%d\" urchin"
</VirtualHost>""".format(hostName=hostName, hostNameshort=hostNameshort, prjDir=prjDir, prjCode=prjCode))
            myFile.close()

我正试图通过这样做使其与 2.4 兼容:

myFile = open(prjFile, 'w+')
myFile.write("""<VirtualHost 192.168.75.100:80>
    ServerName www.%(hostName)s
    ServerAlias %(hostNameshort).* www.%(hostNameshort)s.*
    DocumentRoot %(prjDir)s/html
    CustomLog \\|/usr/sbin/cronolog /var/log/httpd/class/prjCode}/\%(hostName)s.log.%Y%m%d\" urchin"
</VirtualHost>""" % ('hostName', 'hostNameshort', 'prjDir', 'prjCode'))
myFile.close()

但是我的错误是

Traceback (most recent call last):
  File "testfunction.py", line 20, in <module>
    </VirtualHost>""" % ('hostName', 'hostNameshort', 'prjDir', 'prjCode'))
TypeError: format requires a mapping

我已经在这里搜索了答案,但我尝试的任何方法似乎都不起作用。我在这里做错了什么?

最佳答案

错误说明了一切,当它需要映射 (dict) 时,您将 tuple 传递给 __mod__。例如你想要这样的东西:

print """<VirtualHost 192.168.75.100:80>
    ServerName www.%(hostName)s
    ServerAlias %(hostNameshort)s.* www.%(hostNameshort)s.*
    DocumentRoot %(prjDir)s/html
    CustomLog \\|/usr/sbin/cronolog /var/log/httpd/class/prjCode}/\%(hostName)s.log.%%Y%%m%%d\" urchin"
</VirtualHost>""" % dict(hostName='foo',hostNameshort='bar',prjDir='baz')

我还需要做一些其他事情。我需要在这一行添加一个 s:

ServerAlias %(hostNameshort).* www.%(hostNameshort)s.*

而且我需要将最后一行的 % 加倍以转义 '%Y%m%d' 中的百分号

关于Python:2.4 格式字符串不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16921568/

相关文章:

python - 通过条件值识别连续的单元格

python - 如何抑制 Pandas Future 警告?

python - 导入错误 : cannot import name 'ClassVar' after installing airflow

python - 在 Python 中漂亮地打印 JSON.dump 二维数组

python - Numpy,为什么 `x += y` 产生的结果与 `x = x + y` 不同?

python - 我们如何在Python中计算可能性?

python - 为时间戳创建组标识符

python - 神经网络中的 SciPy 优化警告

python - 仅替换一定数量的字符

python - Xcode 8 无法启动 : Loading a plug-in failed