nicer way to remove prefix of a string if it exists
Shashwat Anand
anand.shashwat at gmail.com
Tue Jul 13 22:22:15 EDT 2010
On Wed, Jul 14, 2010 at 5:42 AM, MRAB <python at mrabarnett.plus.com> wrote:
> News123 wrote:
>
>> I wondered about a potentially nicer way of removing a prefix of a
>> string if it exists.
>>
>>
>> Here what I tried so far:
>>
>>
>> def rm1(prefix,txt):
>> if txt.startswith(prefix):
>> return txt[len(prefix):]
>> return txt
>>
>>
>> for f in [ 'file:///home/me/data.txt' , '/home/me/data.txt' ]:
>> # method 1 inline
>> prefix = "file://"
>> if f.startswith(prefix):
>> rslt = f[len(prefix):]
>> else
>> rsl = f
>> # method 2 as function
>> rslt = rm1('file://',f)
>>
>>
>> Is there any nicer function than above rm1()?
>>
>
> No.
>
>
> Is there any nicer inline statement rhan my method 1' ?
>>
>> You could write:
>
> rsl = f[len(prefix):] if f.startswith(prefix) else f
>
Or you can just do split and join, "".join(f.split(prefix, 1)) will do.
>>> prefix = 'file://'
>>> f = 'file:///home/me/data.txt'
>>> "".join(f.split(prefix, 1))
'/home/me/data.txt'
>>> f = 'file:///home/me/data.txtfile://'
>>> "".join(f.split(prefix, 1))
'/home/me/data.txtfile://'
>>> f = '/home/me/data.txt'
>>> "".join(f.split(prefix, 1))
'/home/me/data.txt'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100714/b5d49ab7/attachment-0001.html>
More information about the Python-list
mailing list