0

I am doing the following:

'm:max'.lstrip('m:')
'ax'

What I need to get is remove the "m:" only. I have a lot of other combinations, which I am using to filter search results -- for example"g:Holiday would search a particular category for "Holiday".

Also, sometimes there is no prefix, which would mean it would search all categories.

How would I do this?

4

3 回答 3

7

You are not 100% clear on what the rules are, but if it's simply an issue of removing everything before the first colon, then you can use split:

>>> 'm:abc'.split(':',1)[-1]
'abc'
>>> 'mabc'.split(':',1)[-1]
'mabc'
>>> 'm:a:bc'.split(':',1)[-1]
'a:bc'

The second argument to split limits the number of splits to perform, and the [-1] gets the right part of the split (or the first element if there are no splits).

See the documentation on str.split().

If, however, the colon must be in second position:

def remove_prefix(s):
    return s[2:] if len(s) > 1 and s[1] == ':' else s
于 2013-04-30T19:30:50.203 回答
6

Keep it simple.

prefix = 'm:'
if a.startswith(prefix):
   a = a[len(prefix):]

BTW

'm:max'.lstrip('m:')

this is wrong; lstrip takes a set of characters to strip (order is irrelevant), not an initial substring to optionally strip.

于 2013-04-30T19:34:16.193 回答
1

This is the only way I could figure out how to accomplish the above:

re.sub(r'^[a-z]:','',string)
于 2013-04-30T19:27:35.527 回答