用于范围内的循环增量



为什么"c";在for循环中不是递增的?

def solution(s):
for c in range(len(s)):
if s[c] == s[c].upper():
s = s[:c] + ' ' + s[c:]
c += 1
return s
print(solution('helloWorld'))

输出应该是"hello World",但是,当我添加空间" "时,我也会增加c,但它不起作用。电流输出为'hello World'

您可以想到:

for c in range(len(s)):

由于CCD_ 5是"0";设置";通过每次循环迭代的范围。该范围跟踪它的迭代次数。

我想你的意思是这样的:

def solution(s):
c = 0
while c < len(s):
if s[c] == s[c].upper():
s = s[:c] + ' ' + s[c:]
c += 1
c += 1
return s

之所以会发生这种情况,是因为c会在下一次迭代for c in ...中自动重新设置。通常,当您在迭代某个内容时尝试修改它时,您会遇到这个问题,因为索引不匹配。这是另一个例子。

您可以使用while循环,但实际上,构建一个新的输出字符串更容易:

def solution(s):
out = ''
for c in s:
if c.isupper():  # I also simplified this
out += ' '
out += c
return out
print(solution("helloWorld"))  # -> hello World

尽管如此,最好使用str.join()来构建字符串,比如使用生成器表达式

def solution(s):
return ''.join(' '+c if c.isupper() else c for c in s)
print(solution("helloWorld"))  # -> hello World
是的,因为您没有调用函数。

最新更新