can it be shorter?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jun 6 12:38:27 EDT 2009


On Sun, 07 Jun 2009 00:21:45 +0800, tsangpo wrote:

> "kj" <no.email at please.post> 写入消息 news:h0e3p9$85t
$1 at reader1.panix.com...
>> 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)
>>
>> kynn (lowest-of-the-low python noob)
> 
> look nice, but:
> 
>>>> re.sub('/?$/', '/', 'aaabbb')
> 'aaabbb'
> 
> has no effect. what a pity.


That's because you're doing it wrong. You've added an extra slash: you're 
asking the regex engine to match a backslash *after* the end of the 
string. Obviously that will never match.

>>> re.sub('/?$/', '/', 'aaabbb')  # extra /
'aaabbb'
>>> re.sub('/?$', '/', 'aaabbb')  # no extra /
'aaabbb/'



But before you get too excited, see my previous post: the regex solution 
is more than ten times slower than test-and-concatenate.



-- 
Steven



More information about the Python-list mailing list