Python percent encoding only certain characters in a URL

Question:

I have to percent encode only # character if it appears in a given url. I know that we can encode a URL using urllib.quote. It takes a safe keyword to set a particular character to be safe for the URL. I am looking for something like:

a = 'http://localhost:8001/3.0/lists/list_1.localhost.org/roster/owner#iammdkdkf'
b = urllib.quote(a,unsafe='#')

Regards.

Asked By: darxtrix

||

Answers:

How about a.replace('#','%23')?

Answered By: burnpanck

You can quote each required character (including #) separately and create a dict. Then replace characters in a loop:

import urllib.parse
reserved = {i: urllib.parse.quote(i) for i in R'#<>:"|?*'}
str_var = "report#2022-12-06#10:15:44.html"
for char, ch_pc_enc in reserved.items():
    str_var = str_var.replace(char, ch_pc_enc)
print(str_var)  # report%232022-12-06%2310%3A15%3A44.html
Answered By: Winand