擅长:python、mysql、java
<p>如果不能使用<a href="http://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer">^{<cd1>} module</a>,请首先创建一个生成器函数,该函数将无限期地遍历替换字:</p>
<pre><code>def cycle(string):
while True:
for c in string:
yield c
</code></pre>
<p>然后,稍微调整一下现有功能:</p>
<pre><code>def replace_string(string,word):
new=''
repl = cycle(word)
for i in string:
if i.isalpha():
new = new + next(repl)
else:
new = new+i
return new
</code></pre>
<p>输出:</p>
<pre><code>>>> replace_string("Hello, I'm Greg, are you ok?", "hi")
"hihih, i'h ihih, ihi hih ih?"
</code></pre>
<p>另一种编写方法(但我认为第一个版本更具可读性,因此更好):</p>
<pre><code>def replace_string(string,word):
return ''.join(next(cycle(word)) if c.isalpha() else c for c in string)
</code></pre>