import urllib.parse
def decode_url_string(encoded_str: str, plus_as_space: bool = True) -> str:
"""
Decodes a URL-encoded string using Python's standard library.
:param encoded_str: The URL-encoded string to decode.
:param plus_as_space: If True, treats '+' as spaces (ideal for query strings).
If False, treats '+' literally.
:return: The fully decoded string.
"""
try:
if plus_as_space:
# unquote_plus handles both %xx escapes and '+' to space conversion
return urllib.parse.unquote_plus(encoded_str)
else:
# unquote handles only %xx escapes
return urllib.parse.unquote(encoded_str)
except Exception as e:
print(f"Error decoding string: {e}")
return encoded_str
if __name__ == "__main__":
# Example 1: Standard URL encoding with special characters
sample1 = "Hello%20World%21%20Python%20%26%20Web"
print("--- Example 1: Standard URL Encoding ---")
print(f"Encoded: {sample1}")
print(f"Decoded: {decode_url_string(sample1, plus_as_space=False)}")
# Example 2: Form query string encoding (spaces represented as '+')
sample2 = "name=Jane+Doe&city=New+York&message=Hello%2C+World%21"
print("\n--- Example 2: Query String Encoding ---")
print(f"Encoded: {sample2}")
print(f"Decoded: {decode_url_string(sample2, plus_as_space=True)}")
'''
run:
--- Example 1: Standard URL Encoding ---
Encoded: Hello%20World%21%20Python%20%26%20Web
Decoded: Hello World! Python & Web
--- Example 2: Query String Encoding ---
Encoded: name=Jane+Doe&city=New+York&message=Hello%2C+World%21
Decoded: name=Jane Doe&city=New York&message=Hello, World!
'''