Fly Dangerous o7
Fly Dangerous o7

Reputation: 101

Python URL Encoding with lowercase letters?

When using urllib.parse.quote the encoding is all capitalized. My proxy server is written in C# which excepts the encoding to be lowercased.

For instance, < is encoded(UTF-8) as %3C. However, C#'s WebUtility.UrlDecode(request.RawUrl) is excepting all lowercase lettering: %3c. The result is two systems that can't talk to each other.

C# ASP.NET did have another function that worked with uppercase encoding. This function no longer exists. (Retired) Link to used C# function

import urllib
my_text="?address=This is an Address!&name=This is a test of it all!<.>"
my_url=urllib.parse.quote(my_text)
my_url

I'm hoping to encode the URL on the python side with lowercase letters. Any idea on how to make this happen?

Another possible solution is decoding the URL with capital letters on the C# side, but there doesn't seem to be a function for this. :(

Upvotes: 4

Views: 1995

Answers (2)

li ki
li ki

Reputation: 382

I'm hoping to encode the URL on the python side with lowercase letters. Any idea on how to make this happen?

We have Regex and it's a powerful weapon. Try this:

import re
import urllib.parse  # I'm curious that you just imported `urllib`.


my_text = "?address=This is an Address!&name=This is a test of it all!<.>"
my_url = re.sub(r'%[0-9A-Z]{2}',                             # pattern
                lambda matchobj: matchobj.group(0).lower(),  # function used to replace matched string
                urllib.parse.quote(my_text))                 # input string
my_url

The output is:

%3faddress%3dThis%20is%20an%20Address%21%26name%3dThis%20is%20a%20test%20of%20it%20all%21%3c.%3e

Compare with the original one:

%3Faddress%3DThis%20is%20an%20Address%21%26name%3DThis%20is%20a%20test%20of%20it%20all%21%3C.%3E

This will meet your requirement.


If you want to process multiple URLs in this way, it is better to use regular expression object:

import re
import urllib.parse


my_re = re.compile(r'%[0-9A-Z]{2}')  # pattern

my_text = "?address=This is an Address!&name=This is a test of it all!<.>"
my_url = my_re.sub(lambda matchobj: matchobj.group(0).lower(),  # function used to replace matched string
                   urllib.parse.quote(my_text))                 # input string
my_url

Docs:

Upvotes: 3

banshee_ar
banshee_ar

Reputation: 9

You can use .lower()

my_url="http://mHJKiHgHJKMKLvkdddd.cOm"
my_url.lower()

'http://mhjkihghjkmklvkdddd.com'

Upvotes: 0

Related Questions