0

I remember learning that there is a simple way to insert string segments into other strings quite easily in Python, but I don't remember how it's done. For example, let's say I'm editing HTML with Python and it looks something like this:

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

So, let's say this HTML code is stored in a variable called html. Now, let's say that I want to manipulate this code and enter the following string "My name is Bob" instead of the % in the second b tag.

If anybody knows what I am talking about, please answer, it is a really cool feature that I would like to use. Thank you!

user1094565
  • 9
  • 3
  • 5

3 Answers3

2

You can append % and a tuple of values:

name = "Bob"
html = "Hello, %s" % (name)

Or name the placeholders and use a dictionary:

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

Or use str.format()

html = "Hello, {0}".format("name")

All three result in a string Hello, Bob.

You can also leave a string unbound like this

html = "Hello, %s" 

and then bind the placeholder whenever necessary

print html
>>> Hello, %s
for name in ["John", "Bob", "Alice"]:
    print html % name
>>> Hello, John
>>> Hello, Bob
>>> Hello, Alice
Junuxx
  • 14,011
  • 5
  • 41
  • 71
  • Insertion string ordinals for .format() start at 0, so that example should be `html = "Hello, {0}".format("name")`. – Myk Willis Aug 24 '17 at 02:41
1
html='''<html>
  <b>Hello, World!</b>
  <b>%s</b>
</html>''' % "My name is Bob"

It is simple string formatting. You can also use the following (you can use {variable} multiple times to insert it in multiple places):

html='''<html>
  <b>Hello, World!</b>
  <b>{variable}</b>
</html>'''.format(variable="My name is Bob")

or you can use the following if you want to replace EVERY "%" in that:

html='''<html>
  <b>Hello, World!</b>
  <b>%</b>
</html>'''.replace('%','Hello my name is Bob')
Jeff Tratner
  • 16,270
  • 4
  • 47
  • 67
IT Ninja
  • 6,174
  • 10
  • 42
  • 65
1

There is an easy way that use string template

there is a sample code

import string

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

print htmlTemplate.substitute(dict(variable="This is the string template"))

you can define your variable in template string with $

Pooya
  • 4,385
  • 6
  • 45
  • 73