can it be shorter?
kj
no.email at please.post
Sat Jun 6 17:56:45 EDT 2009
In <h0e9q8$ni7$1 at reader1.panix.com> kj <no.email at please.post> writes:
>In <023a8d04$0$20636$c3e8da3 at news.astraweb.com> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
>>On Sat, 06 Jun 2009 15:59:37 +0000, kj wrote:
>>> In <h0e0oi$1es2$1 at adenine.netfront.net> "tsangpo"
>>> <tsangpo.newsgroup at 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:
>I was just responding to the OP's subject line. Whatever else one
>may say about my proposal, it *is* shorter.
>But thanks for the tip with timeit. That looks like a good module
>to know.
And actually, if speed is the criterion, then one should also avoid endswith:
>>> from timeit import Timer
>>> min(Timer("if s[-1] != '/': s += '/'", "s = 'abcd/efgh'").repeat())
0.18654584884643555
>>> min(Timer("if not s.endswith('/'): s += '/'", "s = 'abcd/efgh'").repeat())
0.43395113945007324
kynn
More information about the Python-list
mailing list