【问题标题】:Adding filename variable into HTML string in Python在 Python 中将文件名变量添加到 HTML 字符串中
【发布时间】:2015-01-22 17:40:29
【问题描述】:

我已经搜索过,但找不到解决方案。我试图让 python 代码循环通过 .mht 文件的目录。找到文件后,它会将 iframe html 代码写入指向 .mht 的文件。我在定义要编写的 iframe 代码并将文件名变量包含在 src 中时遇到问题。

htmlframe = '''<iframe src="'%s.mht'" class="iframe" scrolling="no" frameborder="0" style="width:100%"></iframe><br>''' % os.path.basename

我得到的错误如下:

Traceback (most recent call last):File "move.py", line 52, in <module>
htmlframe = '''<iframe src="'%s.mht'" class="iframe" scrolling="no"
frameborder="0" style="width:100%"></iframe><br>''' % os.path.basename
TypeError: not enough arguments for format string                                                                                                        

提前感谢您的帮助。

【问题讨论】:

  • 你应该尝试用%%引用%

标签: html string variables iframe python-3.4


【解决方案1】:

对于相当复杂的字符串替换操作,您应该查看模板引擎。使用这样的引擎,通常更容易保持概览并在以后进行修改。标准库中内置了一个非常简单的:https://docs.python.org/2/library/string.html#template-strings

大部分时间就够了!

例子:

from string import Template

s = """<iframe src="$filename" class="iframe" scrolling="no"></iframe>"""
t = Template(s)
print t.substitute(filename="foobar.mht")

测试:

python template.py
<iframe src="foobar.mht" class="iframe" scrolling="no"></iframe>

【讨论】:

  • 尝试时,我在 t.substitute 上得到无效的 synatx。
  • 我使用 Python 2.7 执行。你在用什么?请记住,print() 是 Python 3 的函数。
  • 然后就使用print(t.substitute(filename="foobar.mht")),下次可能将python3 作为标签添加到您的问题中? :)
  • 非常感谢!对不起!没有意识到2.7和3.4之间有很大的区别,我还在学习。您知道如何获取filename=foobar.mht 并将其转换为循环所在文件名的变量吗?我查看了 Python 变量,它引导我找到 os.path.basename,但我不知道如何实现它。
猜你喜欢
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多