Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a pipe ( | ) symbol for url_encode in python

Tags:

python

I am facing a problem with urllib.url_encode in python. Bets explained with some code:

>>> from urllib import urlencode
>>> params = {'p' : '1 2 3 4 5&6', 'l' : 'ab|cd|ef'}
>>> urlencode(params)
'p=1+2+3+4+5%266&l=ab%7Ccd%7Cef'

I want to keep the pipes ('|') in to l parameter. can you please tell me how?

The result should be

'p=1+2+3+4+5%266&l=ab|cd|ef'

PS: I do not want to put together the URL manually, but use urlencode for that.

Thanks -Pat

like image 990
wzr1337 Avatar asked Jul 03 '12 19:07

wzr1337


People also ask

How do you escape a pipe in Python?

Python Regex Escape Pipe You can get rid of the special meaning of the pipe symbol by using the backslash prefix: \| . This way, you can match the parentheses characters in a given string. Here's an example: What is this?

How do you pass special characters in a URL in Python?

s = urllib2. quote(s) # URL encode. # Now "s" is encoded the way you need it. It works!

What does Urllib parse Urlencode do?

parse. urlencode() method can be used for generating the query string of a URL or data for a POST request.


1 Answers

Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string[...]

The urlencode() method is acting as expected. If you want to prevent the encoding then you can first encode the entire object and then replace the encoded characters with pipes.

>>> u = urlencode(params)
>>> u.replace('%7C', '|')
'p=1+2+3+4+5%266&l=ab|cd|ef'  
like image 196
Robert Avatar answered Oct 06 '22 11:10

Robert