简体   繁体   中英

Python percent encoding only certain characters in a URL

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.

怎么样a.replace('#','%23')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM