Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串插入_Python_Insertion - Fatal编程技术网

Python字符串插入

Python字符串插入,python,insertion,Python,Insertion,我记得在Python中,有一种简单的方法可以很容易地将字符串段插入到其他字符串中,但我不记得它是如何完成的。例如,假设我正在用Python编辑HTML,它看起来像这样: <html> <b>Hello, World!</b> <b>%</b> </html> 你好,世界! % 假设这个HTML代码存储在一个名为HTML的变量中。现在,让我们假设我想处理这段代码,并输入以下字符串“My name is Bob”,

我记得在Python中,有一种简单的方法可以很容易地将字符串段插入到其他字符串中,但我不记得它是如何完成的。例如,假设我正在用Python编辑HTML,它看起来像这样:

<html>
  <b>Hello, World!</b>
  <b>%</b>
</html>

你好,世界!
%
假设这个HTML代码存储在一个名为HTML的变量中。现在,让我们假设我想处理这段代码,并输入以下字符串“My name is Bob”,而不是第二个b标记中的%


如果有人知道我在说什么,请回答,这是一个非常酷的功能,我想使用。谢谢大家!

您可以附加%和一组值:

name = "Bob"
html = "Hello, %s" % (name)
或命名占位符并使用字典:

html = "Hello, %(name)s" % { name: name }
或使用

这三个结果都是一个字符串
Hello,Bob

您也可以像这样使字符串未绑定

html = "Hello, %s" 
然后在必要时绑定占位符

print html
>>> Hello, %s
for name in ["John", "Bob", "Alice"]:
    print html % name
>>> Hello, John
>>> Hello, Bob
>>> Hello, Alice

您可以附加%和一个值元组:

name = "Bob"
html = "Hello, %s" % (name)
或命名占位符并使用字典:

html = "Hello, %(name)s" % { name: name }
或使用

这三个结果都是一个字符串
Hello,Bob

您也可以像这样使字符串未绑定

html = "Hello, %s" 
然后在必要时绑定占位符

print html
>>> Hello, %s
for name in ["John", "Bob", "Alice"]:
    print html % name
>>> Hello, John
>>> Hello, Bob
>>> Hello, Alice
或者,如果要替换其中的每个“%”,可以使用以下命令:

html=''
你好,世界!
%
''。替换('%',你好,我叫鲍勃')
或者,如果要替换其中的每个“%”,可以使用以下命令:

html=''
你好,世界!
%
''。替换('%',你好,我叫鲍勃')

使用字符串模板有一种简单的方法

这里有一个示例代码

import string

htmlTemplate = string.Template(
"""
<html>
<b>Hello, World!</b>
<b>$variable</b>
</html>
""")

print htmlTemplate.substitute(dict(variable="This is the string template"))
导入字符串
htmlTemplate=string.Template(
"""
你好,世界!
$variable
""")
打印htmlTemplate.substitute(dict(variable=“这是字符串模板”))

您可以使用$

在模板字符串中定义变量有一种使用字符串模板的简单方法

这里有一个示例代码

import string

htmlTemplate = string.Template(
"""
<html>
<b>Hello, World!</b>
<b>$variable</b>
</html>
""")

print htmlTemplate.substitute(dict(variable="This is the string template"))
导入字符串
htmlTemplate=string.Template(
"""
你好,世界!
$variable
""")
打印htmlTemplate.substitute(dict(variable=“这是字符串模板”))

您可以使用$

在模板字符串中定义变量。format()的插入字符串序号从0开始,因此示例应该是
html=“Hello,{0}”。format(“name”)
。format()的插入字符串序号从0开始,因此示例应该是
html=“Hello,{0}”。format(“name”)