-2

I´m trying to write HTML code using python and execute it from browser. Here is my code:

import webbrowser

f = open('image.html','w')

message = """<html>
<head></head>
<body><img src="URL"></body>
</html>"""

f.write(message)
f.close()

filename = 'file:///home/pi/' + 'image.html'
webbrowser.open_new_tab(filename)

Simple code, works like a charm!

Now I want to make little ¨UI¨, so that user will be able to input the URL. So my question is, can I put Python Variable into the HTML code instead of URL? for example:

a = ¨webpage.com/image.jpg¨
...
<img src="a">
...

For sure, I know that the syntax is super wrong, I just wanted to give you an example of what I´m trying to achieve. cheers!

1
  • 2
    String formatting sounds like a topic that would be useful for you to read up on: pyformat.info Commented Aug 10, 2017 at 22:42

2 Answers 2

2

If you are using python 3.6+, you can use formatted strings literals:

>>> URL = "http://path.to/image.jpg"
>>> message = f"""<html>
... <head></head>
... <body><img src="{URL}"></body>
... </html>"""
>>> print(message)
<html>
<head></head>
<body><img src="http://path.to/image.jpg"></body>
</html>
>>>

If you are using python 2.7+ you can use string.format():

>>> URL = "http://path.to/image.jpg"
>>> message = """<html>
... <head></head>
... <body><img src="{}"></body>
... </html>"""
>>> print(message.format(URL))
<html>
<head></head>
<body><img src="http://path.to/image.jpg"></body>
</html>
>>>
Sign up to request clarification or add additional context in comments.

Comments

1

You need to look into variable interpolation (or more generally, string formatting). Take a look at this post. To give you a quick example:

foo = "hello"
bar = """world
%s""" % foo

print bar

...will output...

hello
world

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.