擅长:python、mysql、java
<p>字符串是不可变的。不能更改字符串中的字符,但必须创建新字符串。如果要使用项分配,可以将其转换为列表,操作列表,然后将其连接回字符串。</p>
<pre><code>def loop(s):
for index in range(0, len(s) - 2):
output = list(s) # create list from string
output[index:index+3] = list('***') # replace sublist
print(''.join(output)) # join list to string and print
</code></pre>
<p>或者,只需从与<code>'***'</code>组合的旧字符串片段中创建一个新字符串:</p>
<pre><code> output = s[:index] + "***" + s[index+3:] # create new string directly
print(output) # print string
</code></pre>
<p>还要注意的是,代码中似乎有一些逐个错误,不应该使用<code>input</code>作为变量名,因为它会隐藏同名的内置函数。</p>