Reputation:
I am trying to format a file path inside of a string but it keeps adding extra '\'.
template = "{%% extends 'base.html' %%}"\
"{%% block content %%}"\
" "\
"<h1>%s</h2>"\
" "\
"<p>%s</p> "\
"<p><img src= '%s'></p>"\
"{%% endblock %%}" %(title, text, img_path)
it returns this.
<p><img src= \'myDirectory/scarlett Johanson/1448556501.89.jpg\'></p>{% endblock %}'}
I don't want the \ before the string and after jpg inside the string. I have tried to slice the last character out of the string but it just removes g and leaves \ at the end. what is confusing me though is that it places \ before 'myDirectory.
I am creating the files with
title = time.time()
file_path = os.path.join(BASE_PATH, '%s.jpg') % title
Upvotes: 4
Views: 1971
Reputation: 6478
Just so you can close the question.
When you print a string representation to the console, it is return quoted.
so print(repr('hello'))
will output 'hello'
If the string contain quotes, it will be escaped, even if not escaped before:
print(repr("'hello'"))
gives '\'hello\''
print(repr('\'hello\''))
gives '\'hello\''
print(repr("""'hello'"""))
gives '\'hello\''
Since your are printing a dict that contain a string, the string will get outputted quoted. print({'a', 'hello'})
gives {'a': 'hello'}
Upvotes: 0
Reputation: 2537
I’m sorry I’m not sure what’s causing the error. However, one way to deal with it is to just use replace
. I’m not familiar with your template renderer (I’ve only used jinja2) but it needs to be something like this:
s = s.replace("/","")
Upvotes: 0
Reputation: 591
I don't know if it is the best solution, but maybe you could use this after you create the template variable:
template=template.replace("\\'","'")
I believe that something goes on with quote escaping though, at some other part of your code....
Upvotes: 0
Reputation: 25862
Did you try using tripple quotes with a string formatter?
template = """
{%% extends 'base.html' %%}
{%% block content %%}
<h1>{title}</h2>
<p>{text}</p>
<p><img src={img_path}></p>
{%% endblock %%}
""".format(title=title, text=text, img_path=img_path)
single quotes shouldn't be used for html attributes
try printing your template to see what you get
print(template)
Upvotes: 1