Luis N wrote:
How would I best turn this string:

'2005-01-24 00:00:00.0'

into this string:

'2005%2D01%2D24%2000%3A00%3A00%2E0'

In order to call a URL.

urllib.quote_plus() is intended for this purpose though it doesn't have the result you ask for: >>> import urllib >>> s='2005-01-24 00:00:00.0' >>> urllib.quote_plus(s) '2005-01-24+00%3A00%3A00.0'

Are you sure you need to escape the - and . ?

You can get exactly what you want with a regular expression and the sub() method. One of the cool features of re.sub() is that the replace parameter can be a *function*. The function receives the match object and returns the replacement string. This makes it easy to define replacements that are programmatically derived from the original string:

 >>> import re
 >>> def hexify(match):
 ...   return '%%%X' % ord(match.group(0))
 ...

hexify is the callback function, it will get a single character match and turn 
it into a hex string

 >>> lett_num = re.compile('[^a-zA-Z0-9]')

lett_num is a regular expression that matches everything except letters and 
digits.

 >>> lett_num.sub(hexify, s)
'2005%2D01%2D24%2000%3A00%3A00%2E0'

Kent


I've hunted through the standard library, but nothing seemed to jump out.

Thank You.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Reply via email to