On Sat, 06 Jun 2009 15:59:37 +0000, kj wrote:

> In <h0e0oi$1es...@adenine.netfront.net> "tsangpo"
> <tsangpo.newsgr...@gmail.com> writes:
> 
>>I want to ensure that the url ends with a '/', now I have to do thisa
>>like below.
>>url = url + '' if url[-1] == '/' else '/'
> 
>>Is there a better way?
> 
> It's a pity that in python regexes are an "extra", as it were. Otherwise
> I'd propose:
> 
> url = re.sub("/?$", "/", url)


Thank goodness regexs are an "extra" in Python, because it discourages 
noobs from pulling out the 80 pound sledgehammer of the regex engine to 
crack the peanut of a test-and-concatenate:


>>> from timeit import Timer
>>> min(Timer(
... "if not s.endswith('/'): s += '/'", "s = 'abcd/efgh'").repeat())
0.70030903816223145
>>> min(Timer(
... "sub('/?$', '/', s)", "from re import sub; s = 'abcd/efgh'").repeat())
7.6922709941864014


That's more than ten times slower. Really, a regex is massive overkill 
for a task that simple.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to