PepperoniPizza
PepperoniPizza

Reputation: 9112

escape % character in Python

I have the following string in python, which is then rendered in a template with Django.

link_string = '<a href="/search/?q=%23%s"> %s </a>'

It is a link to a search url where %23 is '#', because I'm trying to search objects with #hashtag.

I intend to interpolate this string with 2 values, %s after the %23 and another one:

link_href = link_string % ('hashtag_value', 'Link Name')

What would be the proper way to obtain the following final string:

<a href="/search/?q=%23hashtag_value"> Link Name </a>

Thank you very much

Upvotes: 0

Views: 618

Answers (3)

bsiamionau
bsiamionau

Reputation: 8229

Just type % character twice

link_string = '<a href="/search/?q=%%23%s"> %s </a>'

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

% is escaped using double percent %%.

Upvotes: 3

Pavel Anossov
Pavel Anossov

Reputation: 62948

link_string = '<a href="/search/?q=%%23%s"> %s </a>'

Upvotes: 3

Related Questions