擅长:python、mysql、java
<h2>最快的方法?</h2>
<p>有三种方法。对于追求速度的人,我推荐“方法2”</p>
<p><strong>方法1</strong></p>
<p>由这个<a href="https://stackoverflow.com/a/1228597/2571620">answer</a>给出</p>
<pre><code>text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)
</code></pre>
<p>比“方法2”要慢得多</p>
<pre><code>timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027
</code></pre>
<p><strong>方法2(快速方法)</strong></p>
<p>由这个<a href="https://stackoverflow.com/a/1228332/2571620">answer</a>给出</p>
<pre><code>text = 'abcdefg'
text = text[:1] + 'Z' + text[2:]
</code></pre>
<p>这要快得多:</p>
<pre><code>timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
0.34651994705200195
</code></pre>
<p><strong>方法3:</strong></p>
<p>字节数组:</p>
<pre><code>timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
1.0387420654296875
</code></pre>