nicer way to remove prefix of a string if it exists

N

News123

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()?
Is there any nicer inline statement rhan my method 1' ?
 
M

MRAB

News123 said:
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

in recent versions of Python, but the function is neater.
 
T

Tim Chase

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.

This suggestion breaks if the prefix occurs within the string
rather than at the beginning:

f = "this has file:// inside it"
prefix = "file://"

So your suggestion really just operates like

f.replace(prefix, '', 1)

-tkc
 
P

Paul McGuire

I wondered about a potentially nicer way of removing a prefix of a
string if it exists.

Here is an iterator solution:

from itertools import izip

def trim_prefix(prefix, s):
i1,i2 = iter(prefix),iter(s)
if all(c1==c2 for c1,c2 in izip(i1,i2)):
return ''.join(i2)
return s

print trim_prefix("ABC","ABCDEFGHI")
print trim_prefix("ABC","SLFJSLKFSLJFLSDF")


Prints:

DEFGHI
SLFJSLKFSLJFLSDF


-- Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top