How to decode URL-encoded and URL query strings in Python

2 Answers

0 votes
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!

'''

 



answered 7 hours ago by avibootz
0 votes
import urllib.parse

def parse_and_decode_query(query_string: str) -> dict:
    """
    Parses a complete URL query string, automatically decoding keys and values 
    into a dictionary. Multiple values for the same key are grouped into a list.
    
    :param query_string: The URL query string (with or without the leading '?').
    :return: Dictionary of decoded keys and lists of decoded values.
    """
    # Remove leading '?' if present
    if query_string.startswith("?"):
        query_string = query_string[1:]
        
    # parse_qs automatically parses parameters and applies URL decoding
    decoded_params = urllib.parse.parse_qs(query_string)
    return decoded_params

if __name__ == "__main__":
    # Sample query string containing encoded parameters and multi-value fields
    full_query = "search=python+tutorial&category=programming&tag=beginner&tag=web"
    
    print("--- Full Query String Parsing ---")
    print(f"Original Query: {full_query}")
    
    result_dict = parse_and_decode_query(full_query)
    
    print("Decoded Dictionary Result:")
    for key, values in result_dict.items():
        print(f"  {key} -> {values}")


'''
run:

--- Full Query String Parsing ---
Original Query: search=python+tutorial&category=programming&tag=beginner&tag=web
Decoded Dictionary Result:
  search -> ['python tutorial']
  category -> ['programming']
  tag -> ['beginner', 'web']

'''

 



answered 7 hours ago by avibootz
...