<p>您希望将<a href="https://docs.python.org/2/library/string.html#string.join" rel="nofollow noreferrer">^{<cd1>}</a>方法与<a href="https://docs.python.org/2/library/string.html#string.split" rel="nofollow noreferrer">^{<cd2>}</a>一起使用。你知道吗</p>
<p>首先<code>split</code><code>"SUPER MAN"</code>通过一个空格得到:</p>
<pre><code>words = "SUPER MAN".split()
["SUPER", "MAN"]
</code></pre>
<p>然后,对于每个条目,使用<code>join</code>用<code>"^"</code>分隔每个字符:</p>
<pre><code>new_words = map(lambda x: "^".join(x), words)
["S^U^P^E^R", "M^A^N"]
</code></pre>
<p>然后使用<code>join</code>将其转换回一个由空格分隔的字符串,得到的代码是:</p>
<pre><code>words = "SUPER MAN".split()
new_words = map(lambda x: "^".join(x), words)
print " ".join(new_words)
</code></pre>
<p>输出:<code>S^U^P^E^R M^A^N</code></p>
<p><strong>代码的作用:</strong></p>
<p>首先,请注意传递到<code>replace</code>的第一个参数不是一个空格,这可能是您想要的,而是表达式<code>"" ""</code>,这是一种进行字符串连接的隐式方法。你知道吗</p>
<p>因此,<code>"SUPER MAN".replace("" "", "^")</code>变为<code>"SUPER MAN".replace("", "^")</code>,它用<code>"^"</code>替换<code>""</code>的每个出现。你知道吗</p>
<p>这样一个操作的结果一开始看起来可能有点定义不清,但是在Python中,由于可以将字符串<code>s</code>视为等于<code>"" + "".join(s) + ""</code>,因此用<code>"^"</code>替换<code>""</code>的每个出现将产生您看到的结果:每个字母之间的<code>"^"</code>和结尾的<code>"^"</code>。你知道吗</p>
<p>将<code>" "</code>作为第一个参数传递给<code>replace</code>是不起作用的,因为它将用<code>"^"</code>替换空格(特别是中间的空格),因此得到<code>"SUPER^MAN"</code>。你知道吗</p>