I have a really noob question here , in php if u wanted to print something inside html you did something like this
<body>
<div>
<?
echo 'Hi i am inside of a div';
?>
</div>
</body>
How do i do that in python?
Dave Chen
11k8 gold badges42 silver badges72 bronze badges
asked Jul 29, 2014 at 2:09
user3854113
1 Answer 1
In a simple case you can use string formatting. Put a placeholder into the string and use format() to substitute the placeholder with the actual text:
html = """
<body>
<div>
{text}
</div>
</body>
"""
print html.format(text='Hi i am inside of a div')
In case of complex HTML structures, you can make use of template languages, like jinja2. You would basically have an html template which you would render with the context provided:
import jinja2
env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('index.html')
print template.render(text='Hi i am inside of a div')
where index.html contains:
<body>
<div>
{{ text }}
</div>
</body>
answered Jul 29, 2014 at 2:14
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
kylieCatt
@Maks if you have complex templates you should look in to using a Web framework like flask, Django or pyramid.
default
html.format(**d)for multiple placeholders.