[Python-ideas] String Subtraction

Dave Jakeman davejakeman at hotmail.com
Thu Oct 14 22:58:52 CEST 2010

I'm new to Python and this is my first suggestion, so please bear with me:

I believe there is a simple but useful string operation missing from Python: subtraction.  This is best described by way of example:

>>> "Mr Nesbit has learnt the first lesson of not being seen." - "Nesbit "
'Mr has learnt the first lesson of not being seen.'
>>> "Can't have egg, bacon, spam and sausage without the spam." - " spam"
'Can't have egg, bacon, and sausage without the spam.'
>>> "I'll bite your legs off!" - "arms"
'I'll bite your legs off!'

If b and c were strings, then:

a = b - c

would be equivalent to:

if b.find(c) < 0:
 a = b
 a = b[:b.find(c)] + b[b.find(c)+len(c):]

The operation would remove from the minuend the first occurrence (searching from left to right) of the subtrahend.  In the case of no match, the minuend would be returned unmodified.

To those unfamiliar with string subtraction, it might seem non-intuitive, but it's a useful programming construct.  Many things can be done with it and it's a good way to keep code simple.  I think it would be preferable to the current interpreter response:

>>> record = line - newline
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

As the interpreter currently checks for this attempted operation, it seems it would be straightforward to add the code needed to do something useful with it.  I don't think there would be backward compatibility issues, as this would be a new feature in place of a fatal error. 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20101014/37dfb0e1/attachment.html>

More information about the Python-ideas mailing list