Search code examples
pythonspecial-charactersencode

Python: encode special character


I'm trying to encode a string containing '-' (minus) symbol to iso8859-15, it will return the string as it is. for eg:

str="abc-def"

Expected output is

abc%2Ddef

Is there any way to do this? sorry me if my question is wrong.


Solution

  • Your output sample suggest you are looking for url encoding, not Latin-1.

    The urllib.quote() and urllib.quote_plus() functions can be used to do such quoting, but the - character does not need quoting and won't be quoted:

    Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted.

    Demo:

    >>> from urllib import quote
    >>> quote('abc-def')
    'abc-def'
    >>> quote('some data that needs quoting!')
    'some%20data%20that%20needs%20quoting%21'
    

    If you are using Python 3, the quote and quote_plus functions are found in the urllib.parse module.