Python. What str.attribute could be used in key argument of method sort? set.sort(key)
<p>I'm a newbie just reading Lutz, so the example is partly from that book:</p>

<pre><code>l = ['aBe', 'ABD', 'abc'] #the following listing works ok
l.sort(key=str.lower)
l
&gt;&gt;&gt;['abc', 'ABD', 'aBe']
</code></pre>

<p>And the quesition is what str.attribute could be used in that case?</p>

<pre><code>l.sort(key=str.replace('Be', 'aa')) #why does not this works for example?
</code></pre>

<p>Thanks a lot for the answers, please don't judge harshly;)</p>

<p>As I  commented, the key must be a callable, to do what you are trying to do you could use a <em>lambda</em> with chained <code>str.replace</code> calls like <code>x.replace("B","a").replace("e","a")</code> but a better solution would be to use <em>str.translate</em>:</p>

<pre><code>tbl = {ord("B"):"a", ord("e"):"a"}

l.sort(key=lambda x: x.translate(tbl))
</code></pre>

<p>Or use <a href="https://docs.python.org/3.6/library/operator.html#operator.methodcaller" rel="nofollow">operator.methodcaller</a> as  <em>Bakuriu</em> commented:</p>

<pre><code>from operator import methodcaller

key=methodcaller('translate', tbl)
</code></pre>

<p>If you just want to match the full substring then it is a simple <code>l.sort(key=lambda x: x.replace("Be","aa"))</code> or <code>l.sort(key=methodcaller("replace","Be","aa"))</code>.</p>

python sorting set