user1100778
user1100778

Reputation: 63

String formatting in python isn't working as expected

I'm building a string via the following:

pagination +='<li>''<a href="/main/?page=%(current_link)s'+link+'">%(current)s</a></li>' % \
                     {'current_link': current_link, 'current': current_link}

When viewing the page in the browser, the text shows up fine but the link points to "..%(current_link)s...". I've tried naming both of them 'current_link' in the string itself but that didn't work so I tried the approach above.

Any suggestions?

Upvotes: 1

Views: 121

Answers (3)

Dirk
Dirk

Reputation: 31061

Hm. You are mixing concatenation with + and formatting with %, and I think, this is a matter of operator precedence: % binds stronger than +, so

("%(a)s" + "%(b)s" % { 'a': 'A', 'b': 'B' }) == '%(a)sB'

Upvotes: 1

Wooble
Wooble

Reputation: 90037

Don't combine cramming strings together with no operator ('foo''bar'), concatenating with +, and formatting with %. You're only formatting the final string.

Upvotes: 0

Rob Wouters
Rob Wouters

Reputation: 16327

The problem is you have separated the string, making the % operator only work on the last part.

Try it like this:

pagination +='<li><a href="/main/?page=%(current_link)s>%(current)s</a></li>' % \
                     {'current_link': current_link, 'current': current_link}

Or if you intended the link variable in there like so:

pagination +='<li><a href="/main/?page=%(current_link)s%(link)s>%(current)s</a></li>' % \
                     {'link': link, 'current_link': current_link, 'current': current_link}

Upvotes: 3

Related Questions