Is it possible to overload the ~ operator on strings?
<pre><code>&gt;&gt;&gt; a = 55
&gt;&gt;&gt; b = "hello"
&gt;&gt;&gt; ~a  # this will work
&gt;&gt;&gt; ~b  # this will fail
</code></pre>

<p>No real surprise for the failure above, but suppose I wanted to overload ~ operator to work on strings. I'm fairly new to Python, so I did some digging on this and found a few tantalizing suggestions that I just couldn't get working. I know I can create some kind of new class, but I'd like the following to work as well:</p>

<pre><code>&gt;&gt;&gt; ~"alpha bravo"
</code></pre>

<p>Is this possible? If so, how? How does one do this kind of overload?</p>

<p>No, this is not possible in Python.  You can not add new methods to built-in types in a way that will work reliably.</p>

<p>One thing you could do is subclass string, and define the magic method <code>__invert__</code>.  But it would not work on string literals, only on instances of your subclass.  </p>

python string overloading operator-keyword