0

Why does "c" in the for loop is not incrementing?

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'))

The output should be "hello World", however, when i add a space " " i also increment the c, but it doesn't works. Current output is 'hello World'

ShibuGuard
  • 11
  • 4

3 Answers3

2

You can think of:

for c in range(len(s)):

as the c being "set" by the range every loop iteration. The range keeps track of what iteration number it's at.

I think you mean something like this:

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
j3st
  • 345
  • 1
  • 8
2

This happens because c is automatically re-set on the next iteration, for c in .... In general, you'll have this problem when you try modifying something while you're iterating over it, because the indices won't match up. Here's another example.

You could use a while loop instead, but actually, it's easier to build a new output string:

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

Although, it's best practice to use str.join() to build strings, like this with a generator expression:

def solution(s):
    return ''.join(' '+c if c.isupper() else c for c in s)

print(solution("helloWorld"))  # -> hello World
wjandrea
  • 28,235
  • 9
  • 60
  • 81
-2

Yes, because you didn't call the function.

  • That seems to be a typo since OP wrote "Current output is `'hello World'`", which is in fact what you get if you run the function – wjandrea Jun 12 '21 at 18:45