擅长:python、mysql、java
<p>使用<code>sys.stdout.write</code>和<em>回车</em><code>\r</code>(允许就地覆盖当前行)和<code>enumerate</code>功能的短进近:</p>
<pre><code>import time
from sys import stdout
string = "this is a test"
for i, c in enumerate(string):
if c:
stdout.write('\r' + string[:i] + c.upper() + string[i+1:])
time.sleep(0.3)
</code></pre>
<ul>
<li><code>if c:</code>条件允许跳过对空白字符的冗余切片和索引</li>
<li>如果您使用的是Python>;=3.6,那么可以使用灵活的<code>f-string</code>样式来构建当前打印的行:<code>stdout.write(f'\r{string[:i]}{c.upper()}{string[i+1:]}')</code></li>
</ul>