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!

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Insertion string ordinals for .format() start at 0, so that example should be html = "Hello, {0}".format("name").
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')

Comments

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 $

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.