<p>你可以用很多方法来解决这个问题。最有效的方法是使用<a href="https://docs.python.org/2/library/random.html" rel="nofollow">^{<cd1>} module</a>。在</p>
<h2><a href="https://docs.python.org/2/library/random.html#random.shuffle" rel="nofollow">^{<cd2>}</a></h2>
<pre><code>>>> from random import shuffle
>>> my_string = list('This is a test string.')
>>> shuffle(my_string)
>>> scrambled = ''.join(my_string)
>>> print(scrambled)
.sTtha te s rtisns gii
</code></pre>
<p>为此,您必须从字符串的字符中创建一个<code>list</code>,因为字符串是<a href="https://docs.python.org/2/glossary.html#term-immutable" rel="nofollow"><em>immutable</em></a>。在</p>
^{bq}$
<h2><a href="https://docs.python.org/2/library/random.html#random.randint" rel="nofollow">^{<cd4>}</a></h2>
^{pr2}$
<p>您不必为此创建<code>list</code>;因为根据<code>random.sample</code>文档:</p>
<blockquote>
<p>Returns a new list containing elements from the population while leaving the original population unchanged.</p>
</blockquote>
<h2><a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow">The ^{<cd7>} built-in</a>带{a6}</h2>
<pre><code>>>> from random import random
>>> my_string = 'This is a test string.'
>>> scrambled = sorted(my_string, key=lambda i: random())
>>> scrambled = ''.join(scrambled)
>>> print(scrambled)
ngi rts ithsT.staie s
</code></pre>
<p>你也不需要这个。来自<code>sorted</code>文档:</p>
<blockquote>
<p>Return a new sorted list from the items in iterable.</p>
</blockquote>
<p>因为在Python中,字符串被视为<a href="https://docs.python.org/2/glossary.html#term-iterable" rel="nofollow">iterable</a>(见下文),因此可以对其使用<code>sorted</code>。在</p>
<p>iterable定义为</p>
<blockquote>
<p>An object capable of returning its members one at a time.</p>
</blockquote>