-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!

  • 2
    String formatting sounds like a topic that would be useful for you to read up on: https://pyformat.info/ – Carter Aug 10 '17 at 22:42

2 Answers2

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>
>>>
Carlangueitor
  • 425
  • 2
  • 15
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
Luke Hollenback
  • 769
  • 6
  • 15