Search code examples
pythonpython-3.xunicodepython-unicode

How to encode/escape unicode text in Python3?


How can I create unicode entities out of python3 string objects?

Having smt _ 1 #, I want to generate smt%20_%201%20%23


Solution

  • Use quote from urllib.parse:

    >>> from urrlib.parse import quote
    >>> quote('smt _ 1 #')
    'smt%20_%201%20%23'
    

    Since you aren't dealing with a url, you don't seem to need to specify any safe characters. If you'd also require / to be escaped, pass safe='' to quote.