首页 > 解决方案 > 范围递增中的 For 循环

问题描述

为什么 for 循环中的“c”不递增?

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'

标签: pythonpython-3.xfor-loop

解决方案


你可以想到:

for c in range(len(s)):

作为c每个循环迭代的范围“设置”。范围跟踪它所处的迭代次数。

我想你的意思是这样的:

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

推荐阅读