Encode URL strings

Run your arguments through this handler before adding them to a URL to make sure special characters are properly encoded to their Hex values.

OS version:

property allowed_URL_chars : (characters of "$-_.+!*'(),1234567890abcdefghijklmnopqrstuvwxyz")
property hex_list : (characters of "0123456789ABCDEF")

return encode_URL_string("Encode me! <steve@mac.com>")

on encode_URL_string(this_item)
	set character_list to (characters of this_item)
	repeat with i from 1 to number of items in character_list
		set this_char to item i of character_list
		if this_char is not in allowed_URL_chars then set item i of character_list to my encode_URL_char(this_char)
	end repeat
	return character_list as string
end encode_URL_string

on encode_URL_char(this_char)
	set ASCII_num to (ASCII number this_char)
	return ("%" & (item ((ASCII_num div 16) + 1) of hex_list) & (item ((ASCII_num mod 16) + 1) of hex_list)) as string
end encode_URL_char

Also:

set txt to "my page.html"
do shell script "python -c 'import sys, urllib; print urllib.quote(sys.argv[1])' " & quoted form of txt
--> "my%20page.html"

hhas has posted this before, but I want to make sure it appears under a Code Exchange search.

Edit: Use urllib.unquote if you want to decode.