DEV Community

Serhat Teker
Serhat Teker

Posted on Originally published at tech.serhatteker.com on

Convert Strings To Be URL Safe

In order to convert your strings to be URL safe you can use python's built-in urllib:

>>> from urllib import parse
>>> string_raw = "Test: Hey! this is an example string"
>>> parse.quote(string_raw)
'Test%3A%20Hey%21%20This%20is%20an%20example%20string'
Enter fullscreen mode Exit fullscreen mode

quote() replaces special characters in string using the %xx escape. Letters, digits, and the characters _.-~ are never touched. By default, this function is intended for converting the path section of a URL.

If you want to use your strings as query strings you can use quote_plus:

>>> from urllib import parse
>>> string_raw = "Test: Hey! this is an example string"
>>> parse.quote(string_raw)
'Test%3A+Hey%21+This+is+an+example+string'
Enter fullscreen mode Exit fullscreen mode

quote_plus() is like quote() but also replace spaces with plus signs. It is required for building HTML form values when building up a query string to go into a URL.

For more info you can look at official python doc: quote, quote_plus

All done!

Top comments (0)