click here" % strLink ...">

Making the right connection with spaces

I have the following code in Python:

linkHTML = "<a href=\"page?q=%s\">click here</a>" % strLink

      

The problem is, when strLink has spaces, the link is displayed as

<a href="page?q=with space">click here</a>

      

I can use strLink.replace ("," + ")

But I'm sure there are other symbols that might cause errors. I tried to use

urllib.quote(strLink)

      

But it doesn't seem to help.

Thanks! Joel

+2


a source to share


2 answers


Make sure you use urllib.quote_plus (string [, safe]) to replace spaces with a plus sign.

urllib.quote_plus(string[, safe])

      

Like quote (), but also replaces spaces with plus signs as required to quote HTML Form Values ​​when creating a query string to navigate to a URL. plus signs in the original string: if not included in safe. It also lacks the default security '/'.



from http://docs.python.org/library/urllib.html#urllib.quote_plus

Ideally, you use the urllib.urlencode function and pass it a sequence of key / value pairs, such as {["q", "with space"], ["s", "with space and others"]}, etc.

+2


a source


Like quote_plus

(*), you also need to HTML-encode any text that you output to HTML. Otherwise, the characters <

, and &

will mark a potential safety implications. (OK, you won't get <

in the url, but you will definitely get &

, so just the parameter name that matches the HTML entity name and your string messes up.

html= '<a href="page?q=%s">click here</a>' % cgi.escape(urllib.quote_plus(q))

      



*: actually plain old quote

is good too; I don't know what doesn't work for you, but this is a great way for url-encoded strings. It converts spaces to %20

, which is also valid and valid in path parts. quote_plus

is optimal for generating query strings, but otherwise, if in doubt, quote

is safest.

+1


a source







All Articles