1

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.

1
  • 1
    Why not just a.replace('#', '%23')? Commented Mar 8, 2015 at 16:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.